I have a div <div id="masterdiv">
which has several child <div>
s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>
s inside the master <div>
using jQuery?
jQuery('#masterdiv div').html('');
jQuery's empty()
function does just that:
$('#masterdiv').empty();
clears the master div
.
$('#masterdiv div').empty();
clears all the child div
s, but leaves the master intact.
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.
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('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$("#masterdiv div").text("");
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();
来源:https://stackoverflow.com/questions/1701973/how-to-clear-all-divs-contents-inside-a-parent-div