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.
Syntax:
$(selector).before(content, function(index))
Parameter | Description |
---|---|
Content | It is a mandatory parameter. It specifies the content to insert.
Its possible values are:
|
Function (index) | It specifies a function that returns the content which is used to insert.
|
Let's take an example to demonstrate the jQuery before() method.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").before("<p><b>Hello rookienerd.com</b></p>"); }); }); </script> </head> <body> <button>Insert content before each p element</button> <p>This is a tutorial website.</p> <p>This is a training institute.</p> </body> </html>
Output:
This is a tutorial website.
This is a training institute.