views:

113

answers:

4

I'm trying to identify an empty element that might or might not contain a comment tag and/or white space.

The following HTML structure is common place in the environment I'm working with:

<div class="container container-no-title">
  <div id="dnn_ctr6735_ContentPane" class="container-padding DNNAlignright">
    <!-- Start_Module_6735 -->
    <div id="dnn_ctr6735_ModuleContent">
      <!-- End_Module_6735 -->
    </div>
  </div>
</div>

My initial jQuery was:

$('.container-padding > div').each(function() {
  if ($(this).is(":empty")) {
    $(this).parent('.container-padding').remove();
  };
});

But this doesn't account for whitespace or comment tags. I found other questions that addressed whitespace, but nothing that addresses comment tags, and I'd really like to keep this little snippet of jQuery simple.

Cheers, Steve

A: 

Comments are not part of the DOM tree, so AFAIK there's no way you could access them.

Darin Dimitrov
This is a nice flat answer and worthy of some applause, but I can't believe there isn't a solution to this!
Steve Perks
+1  A: 

Have you tried:

$('.container-padding > div').each(function() {
    if ($(this).text().match(/^\s*$/)) {
        $(this).parent('.container-padding').remove();
    }
});

Or even

$('.container-padding').each( function() {
    if ($(this).text().match(/^\s*$/)) {
        $(this).remove();
    }
});
tvanfosson
I have, that addressed of the whitespace, but didn't address the comment tag.
Steve Perks
Then why not add a regex test for the comment tag and be done with it?
The Wicked Flea
Do you mean that you don't want to remove the element if there is a comment tag? In my test with your example, this successfully matched and removed the inner container.
tvanfosson
that second solution hit the nail on the head... very much appreciated.
Steve Perks
I have to give you full credit - this solution presented another issue, but you certainly provided the correct answer to the question...
Steve Perks
+1  A: 

If I understand correctly an empty element should have no children:

$(this).children().length == 0

Would'nt jQuery do the work of ignoring whitespace and comments for you?

Brett Pontarelli
I think the idea was that it if it contained only an empty child, comments, or whitespace, it should be removed.
tvanfosson
+1  A: 

glad that tv's solution worked for you. you can also use straight up DOM to find nodes that aren't "elements" by checking the nodeType value.

for example, iterating over element.childNodes:

if (element.childNodes[i].nodeType != 1)
// node is not an element (text/whitespace or comment)

or:

if (element.childNodes[i].nodeType == 8)
// node is a comment

check here for more info.

ob