Reputation: 1920
So essentially I have a ton of paragraph tags that contain non-breaking spaces. While I know, removing them and correcting the issue is the real concern - I'm working on a bandaid fix to auto-remove them after the page loads via jQuery.
Essentially I have:
<p> </p>
Several hundred times in a page.
I want to remove them all via jQuery but of course not remove all the other paragraphs on the page which don't solely contain non-breaking spaces.
This should be fairly simple but for some reason I'm not getting it; something like:
if($.trim($('p').html()) == ' '){
$(this).remove();
}
That is only hitting the first paragraph on the page, I need to hit all of them.
Upvotes: 4
Views: 2189
Reputation: 1074148
jQuery can help you with that:
$("p").html(function(index, oldHtml) {
if (oldHtml === " ") {
$(this).remove();
}
});
That uses the variant of the jQuery html
function that accepts a function. Add a $.trim
if required.
Alternately:
$("p").each(function() {
var $this = $(this);
if ($this.html() === " ") {
$this.remove();
}
});
That uses each
, and then html
to retrieve the HTML of each element. Again, add a $.trim
if required.
Upvotes: 3
Reputation: 10420
Use jQuery's each() function to iterate over every one of them:
$('p').each(function()
{
if ($.trim($(this).html()) == ' ')
{
$(this).remove();
}
}
You can also use the ":contains" selector to only get the paragraphs that contain a non-breaking space:
$('p:contains(" ")')
Upvotes: 2
Reputation: 2871
Your selector is correct. But as soon as you call html()
(or attr()
or text()
or anything like that) it just calls it for the first element matched. So you have to iterate all the elements and test/remove each one of them
$(p).each(function(){
if($.trim($(this).html()) == ' ') {
$(this).remove();
}
});
Upvotes: 1