Reputation:
How can I use jquery to remove a SPECIFIC div that has no children (at least no children that isn't whitespace). E.g.
<div id="outer">
some content
<div id="removeme">
</div>
some more content
</div>
Want to completely remove the div with id="removeme".
Upvotes: 17
Views: 41667
Reputation: 3008
Remove parent if it doesn't have a child with specific class
$('.parentClass:not(:has(.childClass))').remove();
Upvotes: 0
Reputation: 2399
Here is if empty with children then you can point at children and then remove a parent, this dont look at whitespaces it just remove if empty
so like; if li is empty it removes #removeme
if (!$("#tabs ul li").length) $('#tabs').remove();
Upvotes: 0
Reputation: 26619
I went with:
$('#outer > div').filter(function (index) {
return $(this).children().length < 1;
}).remove();
This says:
Sadly, this will remove the div if it contains text, which is probably not what the original poster would have wanted. Plain text doesn't count as a child.
Upvotes: 8
Reputation: 143124
To remove the element with id
equal to removeme
:
$("#removeme").remove();
To remove the element with id
equal to removeme
only if it is empty:
$("#removeme:empty").remove();
To remove all empty <div>
s:
$("div:empty").remove();
EDIT: If it's not empty, but has whitespace:
if($.trim($("#removeme").text()) == "") {
$("#removeme").remove();
}
Upvotes: 50
Reputation: 7441
I couldn't find a selector that ignores text nodes, so this is the quickest/dirtiest code snippet I could come up with.
$("#header").each(function() {
if($(this).children().length < 1)
$(this).remove()
});
Upvotes: 0
Reputation: 29267
I think you want this:
$('div#outer div:empty').remove();
It will remove all the empty divs inside the div#outer node
Upvotes: 0
Reputation: 552
You can also use:
$('div:empty').remove();
http://docs.jquery.com/Selectors/empty
Upvotes: 2