detach method in jQuey with example

1. detach() method removes the matched set of elements from DOM structure.
2. detach() method expects a parameter, which is basically a selector.
3. detach() is same as remove(), but detach() method keeps the jQuery data associated with the remove elements.
4. detach() is more useful when you have to reinsert the remove elements into DOM structure.



Example 1 :


        <html>
        <head>
        <title>detach</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 () {
                $("#detach").click(function () {
                    $("#targetP").detach();
                });
            });
        </script>
        </head>
        <body>
        <p id="targetP">This is 99codingexample.</p>
        <input type="button" id="detach" value="Detach"/>
        <input type="button" id="reset" value="Reset" onclick="location.reload()" />
        </body>
        </html>
    
Demo :



In above example, we have rendered a pragraph element. On click of "Detach" button, paragraph element is selected using id selector and detached or removed from DOM structure using detach() method.



Example 2 :



        <html>
        <head>
        <title>detach</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 () {
                var p;
                $("#detach").click(function () {
                    p = $("p").detach();
                });
                $("#attach").click(function () {
                    $("#targetDiv").append(p);
                });
            });
        </script>
        </head>
        <body>
        <div id="targetDiv">
        <p>This is 99codingexample.</p>
        </div>
        <input type="button" id="detach" value="Detach"/>
        <input type="button" id="attach" value="Attach"/>
        <input type="button" id="reset" value="Reset" onclick="location.reload()" />
        </body>
        </html>
    
Demo :




In above example, we have used detach() method to detach paragraph element from DOM structure. We have assigned paragraph element to a variable.
    On click of "Detach" button paragraph element is detached and is stored in variable. On click of "Attach" button, paragraph element is appended back to the div element using append() method. This example shows that detach() method keeps information of removed elements, and can be attached later.



Watch Video :



0 comments:

Post a Comment