How to use the insertBefore() in jQuery .

The insertBefore() method is use when we want to insert HTML elements before the selected elements.

Step 1 Create a HTML page Here we create a html page named test.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>This is a default paragraph.</p>

<button>Insert </button>
</body>
</html>
Step 2 Add the jQuery script in head section page like below.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
Step 3 Now Finally, apply the insertBefore function inside script tag like below or according to your requirement.

<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span>This text will be shown before p tag.</span>").insertBefore("p");
  });
});
</script>
The Compete HTML page will be look like below.

<!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(){
    $("<span>This text will be shown before p tag.</span>").insertBefore("p");
  });
});
</script>
</head>
<body>
<br>
<p>This is a default paragraph.</p>

<button>Insert </button>
</body>
</html>
Output of page before click on button.

The above output will be shown when the user loads the test.html page.
Output after click on Insert button.

Notice that “This text will be shown before p tag.” this line is newly added just before p tag, as we mention in script. How to use the insertBefore() in jQuery.expoundsofttechsolution How to use the insertBefore() in jQuery.