We can use the jQuery before method to insert a new HTML element before another element.

$("#div2").before("
");

Let’s take a look at a quick example.


Let’s say we have the following HTML:

This is paragraph 2

This is paragraph 3

If we want to insert a new paragraph before paragraph with class “p2”, then we can use the jQuery before() method to do this with the following jQuery code.

$(".p2").before("

This is paragraph 1

");

The result would be as follows:

This is paragraph 1
This is paragraph 2
This is paragraph 3

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery(".p2").before("

This is paragraph 1

");

If you want to insert HTML after another element, we can do this with the jQuery after() method.

Using the jQuery before() Method to insert HTML before a Div on a Click

In this example, we will have a div that will be a box. We will then let the user insert a new box we create using the before() method as many times as they want.

Here is the HTML code:



Insert new box

The new code to create a box will just be a new div with the class “box”.

We will change the new box background color using the css() method and add it as a style attribute.

Also note that our original box will have a black border on it so we can keep track of it as we add boxes.

Here is the jQuery and JavaScript code:

$("#click-me").click(function(){
  //Create a random color
  var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
  //Create a new div with class box, and add the new color to it as a bg  
  $('#first-box').before("
"); });

The final code and output for this example of using the jQuery before() method to create a bunch of new box divs is below:

Code Output:

Insert new box

Full Code:



Insert new box

Hopefully this article has been useful for you to understand how to use the jQuery before method.

Categorized in:

jQuery,

Last Update: February 26, 2024