Tuesday, March 1, 2011

clear all divs' contents inside a div

I have a div <div id="masterdiv"> in which i will have several child divs.

For example:

<div id="masterdiv">
    <div id="childdiv1" />
    <div id="childdiv2" />
    <div id="childdiv3" />
</div>

I need to clear the contents of all child divs inside the master div using jquery.

How to achieve it?

From stackoverflow
  • $("#masterdiv div").text("");
    
  • jQuery('#masterdiv div').html('');
    
    Prasad : Can we clone the html and manipulate on that? like var tmp = $('
    ').append($('#masterdiv').clone()).remove().html(); and get the divs inside #masterdiv of tmp and clear the contents and return
    Drew Noakes : Using `.empty()` would be a better option as no string parsing is involved. It operates directly on the DOM object model.
  • If all the divs inside that masterdiv needs to be cleared, it this.

    $('#masterdiv div').html('');
    

    else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.

    $('#masterdiv div).each(
        function(element){
         if(element.attr('id').substr(0, 8) == "childdiv")
         {
          element.html('');
         }
        }
     );
    
  • $("#masterdiv > *").text("")
    

    or

    $("#masterdiv").children().text("")
    
  • jQeury's empty() function does just that:

    $('#masterdiv').empty();
    
  • $("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty;});
    

    or

    $("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty;});
    
  • Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.

    $('#masterdiv div').empty();
    

    Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.

0 comments:

Post a Comment