insertBefore method in jQuery with example

1. insertBefore() method inserts every element in the set of matched elements before the target.

Example 1 :

        <script type="text/javascript" src=""> 
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myButton").click(function () {
                    $("<span>This is span element.</span><br/>").insertBefore($('#targetP'));
        <p id="targetP">This is p element. On clicking the button span will be added before the p element.</p>
        <br />
        <input type="button" id="myButton" value="Click ME"/>
        <input type="button" value="Reset" onclick="location.reload()"/>
Demo :

In above example, we are using insertBefore() method to insert span element before the target element specified as selector to insertBefore() method.


Post a Comment