John
John

Reputation: 627

How do I remove empty elements from the dom using jQuery?

The WordPress word editor spits out empty <p> tags like this: <p>&nbsp;</p>.

I would like to target all <p> with &nbsp; in them and remove them. I believe I have to use the contains and remove functions but I am not sure if this code would remove the <p> tags with only &nbsp; in them or remove all <p> tags with &nbsp; in them anywhere.

jQuery('p:contains("&nbsp;")').remove();

How would I make this work?

Upvotes: 7

Views: 4502

Answers (1)

voigtan
voigtan

Reputation: 9031

you can use .filter and look if the innerHTML is equal to  :

$("p").filter(function(){
    return $.trim(this.innerHTML) === "&nbsp;"
}).remove();

Upvotes: 11

Related Questions