开发者

in jQuery, how to remove an element that has only one whitespace?

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'> </s开发者_高级运维pan>
<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?


       $('span').each(function(){
               var str = $(this).text().replace(/ /g,'');
               if (str.length < 1){
                   $(this).remove();
               }
          });


This should do it:

$("span[class*='test2']").filter
                (
                  function() {
                      return $(this).text() === " ";
                  }
                ).remove();


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+/);
    }
});


For people that use coffee script and want to remove tags with one or more whitespaces.

for paragraph in $('p')
    str = $(paragraph).text().replace(/\s+/,'')
    if str.length < 1
        $(paragraph).remove();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜