empty method in jQuery with example

1. empty() method removes all the child nodes of matched elements from the DOM structure.
2. empty() and detach() methods are same, only difference is detach() keeps the information of removed elements.

Example 1 :

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        <script type="text/javascript">
            $(document).ready(function () {
                $("#empty").click(function () {
        <div id="targetDiv">
        <p>This is p element inside div.</p>
        <span>This is span element inside div.</span>
        <h4>This is h4 element inside div.</h4>
        </div><br />
        <input type="button" id="empty" value="empty"/>
        <input type="button" id="reset" value="Reset" onclick="location.reload()" />
Demo : 

In the above example, we have created a div element. Inside this div element we have nested elements. We have rendered a empty button. On click of this button the entire div is selected and its child nodes are removed from DOM structure using empty() method.


Post a Comment