In jQuery, how to remove an item with a single space?

Given the following HTML on the 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 row <span class='test2'> </span>using jQuery?

If this helps anyone, I can find it through regex:

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

And I can find and remove any node with this class using jQuery:

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

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

I feel that I am very close, but I am missing something; I would like to get the result:

<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?

+3
source share
4 answers

This should do it:

$("span[class*='test2']").filter
                (
                  function() {
                      return $(this).text() === " ";
                  }
                ).remove();
+2
       $('span').each(function(){
               var str = $(this).text().replace(/ /g,'');
               if (str.length < 1){
                   $(this).remove();
               }
          });
+3

, , : contains() . .

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

For people who use a coffee script and want to remove tags with one or more spaces.

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

Source: https://habr.com/ru/post/1729656/


All Articles