How can I select the entire empty tag using jQuery.?

How can I select the entire empty tag using jQuery.

I want to choose

<p></p> <p style="display: block"></p> <p> </p> <p> </p> <p>&nbsp;</p> 

but not

 <p>0</p> <p>Test</p> 

I tried with :empty , but it does not work with my options. Any help on this is greatly appreciated.

+6
source share
5 answers

You can do this using jQuery.filter() .

 var empty_p = $('p').filter(function(){ return !$.trim($(this).text()); }).get(); 
+7
source

Use the jQuery filter :

 $('p').filter(function () { return !$(this).text().trim(); }); 
+2
source
 $(document).ready(function(){ $("p").each(function(index){ var html = $(this).html(); html = filter(html, " "); html = filter(html, "&nbsp;"); if ($(this).html() == ""){ //YOUR CODE } }); }); function filter(string, char){ while(string.indexOf(char) > 0){ string.replace(char, ""); } } 

JS FIDDLE

+1
source

You can do this using jquery filter and trim . Here is a working example: http://jsfiddle.net/snqSw/

 $("p").filter(function(){ $(this).text($.trim($(this).text())==""?"Works":$(this).text()); }); 
0
source

Another way to do this is using regular expressions instead of trim() :

 $('p').filter(function () { return !/\S/.test( $(this).text() ); }) 

( JSFiddle )

Note that this (and any other solution based on $(this).text() ) will also match, for example. this item:

 <p><a href="http://example.com">&nbsp;</a></p> 

or even:

 <p><img src="http://example.com/image.gif"></p> 

Depending on what you want to do with the paragraphs, this may or may not be what you want. If this is not the case, you will need something more complex; the details will depend only on what exactly you would like to consider the "blank" paragraph.

-1
source

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


All Articles