We can use the jQuery before method to insert a new HTML element before another element.
$("#div2").before("<div id='div1'></div>");
Let’s take a look at a quick example.
Let’s say we have the following HTML:
<div id="div1">
<p class="p2">This is paragraph 2</p>
<p class="p3">This is paragraph 3</p>
</div>
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("<p class='p1'>This is paragraph 1</p>");
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("<p class='p1'>This is paragraph 1</p>");
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:
<style>.box{ float: left; width: 50px; height: 50px; background: #7bbfa2; margin-right: 10px; margin-bottom: 10px; }</style>
<div id="div2">
<div id="first-box" class="box" style="border: 2px solid #000;"></div>
</div><div class="clear"></div>
<div id="click-me">Insert new box</div>
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("<div class='box' style='background: " + randomColor + ";'></div>");
});
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:
Full Code:
<style>.box{ float: left; width: 50px; height: 50px; background: #7bbfa2; margin-right: 10px; margin-bottom: 10px; }</style>
<div id="div2">
<div id="first-box" class="box" style="border: 2px solid #000;"></div>
</div><div class="clear"></div>
<div id="click-me">Insert new box</div>
<script>
$("#click-me").click(function(){
var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
$('#first-box').before("<div class='box' style='background: " + randomColor + ";'></div>");
});
</script>
Hopefully this article has been useful for you to understand how to use the jQuery before method.
Leave a Reply