jQuery before() Method

jQuery before() method insert content before selected elements.

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

Use the after() method to insert content after the selected elements.

Syntax

This syntax represent to the before() method

$(selector).before( content, function(index) );
Parameter Type Description
content htmlString
Element
Text
Array
jQuery
Required. HTML string, DOM element, text node, array of elements, or jQuery object to insert before selected elements.
function(index) Function Optional. A function that returns an HTML string, DOM element, text node, array of elements, or jQuery object to insert before selected elements.
  • index - Return the index position of the element in the set as an argument.

Example

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

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

Run it...   »