jQuery before()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery before()

The jQuery before() method is used to insert the specified content before the selected elements. It adds the content specified by the parameter, before each element in the set of matched elements.

The before() and insertBefore() both methods are used to perform same task. The main difference between them is in syntax, and the placement of the content and the target.

Syntax:

  1. $(selector).before(content, function(index))  

Parameters of jQuery before() method

Parameter Description
Content It is a mandatory parameter. It specifies the content to insert. Its possible values are:
  • HTML elements
  • jQuery objects
  • DOM elements
Function (index) It specifies a function that returns the content which is used to insert.
  • Index: It provides the index position of the element in the set.

Example of jQuery before() method

Let's take an example to demonstrate the jQuery before() method.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("button").click(function(){  
  8.         $("p").before("<p><b>Hello javatpoint.com</b></p>");  
  9.     });  
  10. });  
  11. </script>  
  12. </head>  
  13. <body>  
  14. <button>Insert content before each p element</button>  
  15. <p>This is a tutorial website.</p>  
  16. <p>This is a training institute.</p>  
  17. </body>  
  18. </html>  

Test it Now

Output:

Insert content before each p element

This is a tutorial website.

This is a training institute.