insertBefore method in jQuery with example


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



Example 1 :



        <html>
        <head>
        <title>insertBefore</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myButton").click(function () {
                    $("<span>This is span element.</span><br/>").insertBefore($('#targetP'));
                });
            });
        </script>
        </head>
        <body>
        <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()"/>
        </body>
        </html>
    
Demo :



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


0 comments:

Post a Comment