Search code examples
jqueryregexjquery-selectorsis-empty

How does jQuery "empty:"-selector works? (remove empty tags)


I'm trying to remove all the empty tags from DOM-tree. Empty means both completely empty (like <a></a>) and with several whitespaces (like <a> ...</a>). Also inner empty tags should also be removed. E.g.

<p style="text-align:right;">     <a> </a>  <a></a></p><p>Hello</p>

should leave

<p>Hello</p>

Because after deleting empty <a> </a> <a></a> an empty <p style="text-align:right;"> </p> would still remain and should be removed.

What I'm doing:

$.(".container>*:empty").remove();

And the result was confusing. I've started to debug with such code:

console.log($.(".container>*:empty").size());

1) String:

Well, though it looks like a paragraph, it's not o_O.
0 (I'm wrapping string in global wrapper .container)

2) String

<a></a><a>Well, though it looks like a paragraph, it's not o_O.</a>
1

3) String

<a> </a><a>Well, though it looks like a paragraph, it's not o_O.</a>
0 (It seems one whitespace makes a non-empty)

4) String

<p> <a></a></p>  <a>Well, though it looks like a paragraph, it's not o_O.</a>
0 (<a></a> is not selected as empty (maybe 'cause it's inside of < p>). 
   Also p is not selected, besides it contains only empty < a>)

My questions are:

  • how to make :empty select both empty tags and with 1-N whitespaces?
  • how to make :empty select all the empty tags inside every objects?

My idea is to do ${"*:empty"}.remove() while $('*:empty').size() > 0.

UPDATE:

do {
$(".container *").filter(function() {
    return $.trim(this.innerHTML) === ""
}).remove();
} while ($(".container *").filter(function() {
return $.trim(this.innerHTML) === ""
}).size() > 0)
console.log($(".container").html())

Apply this code to:

<p> <p> <a> <a>  <a><br><hr></a> </p>  <a>Well, though it looks like a paragraph, it's not o_O.</a></p>

And we get:

<p>   <a>Well, though it looks like a paragraph, it's not o_O.</a></p>

Solution

  • You should look at filter() and trim():

    DEMO

    $(".container *")
        .filter(function(){
             return $(this).is(':not(br)') 
                    && $(this).is(':not(img)') 
                    && $.trim(this.innerHTML) === ""
         }).remove();