views:

1039

answers:

7

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?

+1  A: 
$("#masterdiv div").text("");
brendan
+8  A: 
jQuery('#masterdiv div').html('');
David Dorward
Can we clone the html and manipulate on that?like var tmp = $('<div>').append($('#masterdiv').clone()).remove().html();and get the divs inside #masterdiv of tmp and clear the contents and return
Prasad
Using `.empty()` would be a better option as no string parsing is involved. It operates directly on the DOM object model.
Drew Noakes
+3  A: 

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('');
     }
    }
 );
Ikke
+1  A: 
$("#masterdiv > *").text("")

or

$("#masterdiv").children().text("")
adamse
+8  A: 

jQeury's empty() function does just that:

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

or

$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty;});
andres descalzo
A: 

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.

Drew Noakes