Description:
The jQuery before() method is used to insert content before the selected element.
Syntax
- $(selector).before(content)
- $(selector).before(content, function(index)) ย
Content | It specifies the content which need to append. |
Function(index) | It specifies the function that returns the content which used to insert.
index: Get the index position of the element in the set |
Passing Function:
.before()
supports passing a function that returns the elements to insert like as below.ย Itย can accept any number of additional arguments like prepend(), after().
1 2 3 |
$("#divcontainer").before(function () { return "<div>Welcome to Dotnet-helpers.com</div>"; }); |
Example:ย
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <style> .container { border: 5px solid #1a80b6; padding: 10px; display: inline-block; } </style> <script type="text/javascript"> $(document).ready(function () { $('#btnClick').click(function () { $("#divcontainer").before('<div style="color:#ff0000"> This is Newly added text </div>'); }) }); </script> </head> <body> <button id="btnClick">Click to Add content using before()</button><br /><br /> <div id="divcontainer" class="container"> <div> This is Default text </div> </div> </body> </html> |
Output:ย
By clicking the button, “this is Newly added text” will append befor the selected div (divcontainer).
Leave A Comment