Insert content before each <p> element:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>//from ww w. j av a 2 s. com <script> $(document).ready(function(){ $("button").click(function(){ $("p").before("<p>Hello world!</p>"); }); }); </script> </head> <body> <button>Insert content before each p element</button> <p>This is a paragraph.</p> <p>This is a paragraph.</p> </body> </html>
The before()
method inserts specified content before the selected elements.
To insert content after selected elements, use the after()
method.
$(selector).before(content,function(index))
Parameter | Optional | Description |
---|---|---|
content | Required. | the content to insert Possible values: HTML elements jQuery objects DOM elements |
function(index) | Optional. | sets a function that returns the content to insert index - the index position of the element in the set |