jQuery insertBefore() Method

jQuery insertBefore() method inserts HTML elements before the selected elements.

jQuery insertBefore() method and before() method perform the same function. There is one major difference is in the syntax, placement of the content and target element.

Use the insertAfter() method to insert HTML elements before the selected elements.

Syntax

Here is a syntax for insertBefore() method

$(content).insertBefore(selector);
Parameter Type Description
content String Required Specifies the HTML content to insert.
selector Selector Required Specifies the selector expression, where to insert the content.

Example

Here, in this example insertBefore() method apply on selected elements when click on button.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery insertBefore() method</title>
  <script src="jquery-latest.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("<p>New text come before the selected element.</p>").insertBefore("p");
      });
    });
  </script>
</head>
<body>
  <div>
    <p>First paragraph start here...</p>
  </div>
  <button>Click Me</button>
</body> 
</html>

Run it...   »