Thursday, December 27, 2012

Jquery - Difference between Remove and Detach


hide() sets the matched elements' CSS display property to none.
remove() removes the matched elements from the DOM completely.
detach() is like remove(), but keeps the stored data and events associated with the matched elements.


Following Examples results only for Div2 and not for Div1

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">

        $(document).ready(function () {
     
            $('#div1').bind('click', function () { alert('div1 click'); });
            $('#div2').bind('click', function () { alert('div2 click'); });

            var div1 = $("#div1").remove();
            var div2 = $("#div2").detach();

            div1.appendTo('body');
            div2.appendTo('body');

        });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div class="container">
            <div id="div1" >
                div1 text</div>
            <div id="div2">
                div2 text</div>
         </div>
    </div>
    </form>
</body>
</html>