Steve Perks
Steve Perks

Reputation: 5530

How does one identify an empty element using jQuery that might contain a comment tag?

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

Upvotes: 1

Views: 1097

Answers (4)

Omer Bokhari
Omer Bokhari

Reputation: 59578

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.

Upvotes: 1

Brett Pontarelli
Brett Pontarelli

Reputation: 1728

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?

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532435

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();
    }
});

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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

Upvotes: 0

Related Questions