JQuery Change all <element> HTML if HTML = something

So essentially I have a ton of paragraph tags that contain inextricable spaces. Although I know that removing them and fixing the problem is a real problem - I am working on fixing a bandai to automatically remove them after the page loads through jQuery.

Essentially I have:

 <p>&nbsp;</p> 

A few hundred times per page.

I want to delete them all through jQuery, but of course I do not delete all the remaining paragraphs on the page that not only contain inextricable spaces.

It should be pretty simple, but for some reason I am not getting it; sort of:

 if($.trim($('p').html()) == '&nbsp;'){ $(this).remove(); } 

This only applies to the first paragraph on the page, I need to hit them all.

+4
source share
4 answers

jQuery can help you with this:

 $("p").html(function(index, oldHtml) { if (oldHtml === "&nbsp;") { $(this).remove(); } }); 

Living example

This uses a variant of the jQuery html function that accepts the function . Add $.trim if necessary.

As an alternative:

 $("p").each(function() { var $this = $(this); if ($this.html() === "&nbsp;") { $this.remove(); } }); 

Living example

Uses each and then html to retrieve the HTML code of each element. Add $.trim if necessary.

+3
source

Use the jQuery each () function to iterate over each of them:

 $('p').each(function() { if ($.trim($(this).html()) == '&nbsp;') { $(this).remove(); } } 

You can also use the ": contains" selector to get only paragraphs containing inextricable space:

 $('p:contains("&nbsp;")') 
+2
source

Your selector is correct. But as soon as you call html() (or attr() or text() or something like that), it just calls it for the first matching element. Thus, you need to iterate over all the elements and test / delete each of them.

 $(p).each(function(){ if($.trim($(this).html()) == '&nbsp;') { $(this).remove(); } }); 
+1
source

If they are all like that, I would use a regex.

0
source

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


All Articles