views:

101

answers:

3

Given the following HTML on a page:

<div class='test'>
<p><span id='id1' class='test1 test2 test3'>test text 1</span></p>
<p><span id='id2' class='test1 test2'>test text 2</span></p>
<span class='test2'> </span>
<p><span id='id3' class='test1'>test text 3</span></p>
<p><span id='id4' class='test1 test3 test2'>text4</span></p>
</div>

How can I completely remove the 4th line <span class='test2'> </span> using jQuery?

If it helps any, I'm able to find it via regex:

var re = new RegExp("<span[^>]*test2[^>]*> </span[^>]*?>");

And I'm able to find and remove any node with that class using jQuery:

$("span[class*='test2']").remove();

But this removes ALL nodes that have the class "test2" which is not what I want; I only want to remove the one with the single whitespace in it. $("span[class*='test2']:empty").remove(); does not work as that node is not empty, and has a whitespace.

I feel I'm very close, but I'm missing something; I would like the result to be:

<div class='test'>
<p><span id='id1' class='test1 test2 test3'>test text 1</span></p>
<p><span id='id2' class='test1 test2'>test text 2</span></p>
<p><span id='id3' class='test1'>test text 3</span></p>
<p><span id='id4' class='test1 test3 test2'>text4</span></p>
</div>

Any clues?

A: 

I don't think you can match any whitespace, since :contains() can't do regex. You could loop on them, or write your own filter.

$.extend($.expr[':'], {
    whitespace: function(el) {
        return $(el).text().search(/\s+/);
    }
});
ironfroggy
+1  A: 

This should do it:

$("span[class*='test2']").filter
                (
                  function() {
                      return $(this).text() === " ";
                  }
                ).remove();
wsanville
that did the trick! thanks
James Nine
this would only work if there is only one space...
Reigel
yup, I only want one space, as clarified in the title.
James Nine
A: 
       $('span').each(function(){
               var str = $(this).text().replace(/ /g,'');
               if (str.length < 1){
                   $(this).remove();
               }
          });
Reigel
this will remove all whitespace and remove the element with no remaining character in it.
Reigel