The jQuery insertBefore() method inserts the specified html elements before the selected elements. If the specified html element is already present in the html page then, the existing element will be moved from the current position and inserted before the selected elements.
Syntax of jQuery insertBefore() method
$(content).insertBefore(selector)
content: This is a mandatory parameter. This contains HTML elements that are inserted before the selected elements by insertBefore() method. This content parameter must always contain html tags.
Important Note: If content field contains already existing html elements then those elements will be moved from the current position and inserted before the selected elements.
selector: This is also a mandatory parameter. This selects the elements before which the specified content is inserted.
jQuery insertBefore() method Example
In the following example, we have a div element which we want to insert before each p element. This can be done using the insertBefore() method.
Here div is specified as content and in the selector field p is mentioned, which represents the paragraph elements. The insertBefore() method moved the existing div element from its current place and inserted before each paragraph (p element).
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").insertBefore("p");
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<div><b><i>Hi, BeginnersBook.com Readers!</i></b></div>
<p>To move and insert the div element before each paragraph click the button below:</p>
<button>Move the div before each p element</button>
</body>
</html>
Output:
Before the button click:
After the button click:
Leave a Reply