So I am receiving unclean content from an API that our content publishers are using and I am getting P tags with non-breaking spaces inside of them and I want to remove the non-breaking space and the P it is in. It would be nice if they cleaned up their content before they published it to the API, but I just need a quick way to remove this via JavaScript or jQuery. I get this error when using the code below. "Syntax error, unrecognized expression: " Thanks for any help.
<p> </p>
$("p").each(function() {
$(this).find(' ').remove();
});
Select your paragraph elements, filter out the ones that contain only
using .filter()
, then use .remove()
:
$('p').filter(function(){
return this.innerHTML == ' ';
}).remove();
Or:
$('p').filter(function(){
return !$.trim($(this).text());
}).remove();
Which, because .text()
handles HTML decoding for you and $.trim()
removes outer whitespace, will remove any paragraph that contains only spaces I.E
<p> </p>