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?
-
$("#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 returnDrew 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
divelements inside the element with idmasterdiv. Then callempty()to clear the contents.$('#masterdiv div').empty();Using
text('')orhtml('')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