In jQuery, you can use the insertBefore()
method to insert an element before another element in the DOM (Document Object Model). The insertBefore()
method allows you to specify the target element and the element to be inserted. Here’s the syntax:
$(elementToInsert).insertBefore(targetElement);
elementToInsert
is the element you want to insert.targetElement
is the element before which you want to insertelementToInsert
.
jQuery insertBefore() Method example
Simple example code that demonstrates the usage of the insertBefore()
method in jQuery:
<!DOCTYPE html>
<html>
<head>
<title>jQuery insertBefore() Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Create a new element
var newElement = $('<h2>New Heading</h2>');
// Insert the new element before the target element
newElement.insertBefore('#target');
});
</script>
</head>
<body>
<div id="target">
<p>Target Element</p>
</div>
</body>
</html>
Output:
Inside the $(document).ready()
function, we create a new <h2>
element with the text “New Heading” using $('<h2>New Heading</h2>')
. Then, we call insertBefore('#target')
on the new element to insert it before the element with the ID target
.
Do comment if you have any doubts or suggestions on this jQuery method code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version