FlyByQuestionGuy
FlyByQuestionGuy

Reputation:

Use jquery to remove a div with no children

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

Answers (7)

Muhammad Bilal
Muhammad Bilal

Reputation: 3008

Remove parent if it doesn't have a child with specific class

$('.parentClass:not(:has(.childClass))').remove();

Upvotes: 0

Simon Dragsb&#230;k
Simon Dragsb&#230;k

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

Jonathan
Jonathan

Reputation: 26619

I went with:

$('#outer > div').filter(function (index) { 
    return $(this).children().length < 1; 
}).remove();

This says:

  • give me all the div children of #outer
  • use filter to get rid of any which have child nodes
  • remove anything we still have selected

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

Sophie Alpert
Sophie Alpert

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

Samantha Branham
Samantha Branham

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

Luca Matteis
Luca Matteis

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

rmurphey
rmurphey

Reputation: 552

You can also use:

$('div:empty').remove();

http://docs.jquery.com/Selectors/empty

Upvotes: 2

Related Questions