Christopher Cooper
Christopher Cooper

Reputation: 1920

jQuery Change All <element> HTML IF that HTML = Something

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>&nbsp;</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()) == '&nbsp;'){
$(this).remove();
}

That is only hitting the first paragraph on the page, I need to hit all of them.

Upvotes: 4

Views: 2189

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

jQuery can help you with that:

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

Live example

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() === "&nbsp;") {
      $this.remove();
  }
});

Live example

That uses each, and then html to retrieve the HTML of each element. Again, add a $.trim if required.

Upvotes: 3

pilsetnieks
pilsetnieks

Reputation: 10420

Use jQuery's each() function to iterate over every one of them:

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

You can also use the ":contains" selector to only get the paragraphs that contain a non-breaking space:

$('p:contains("&nbsp;")')

Upvotes: 2

jgradim
jgradim

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()) == '&nbsp;') {
    $(this).remove();
  }
});

Upvotes: 1

LunaCodeGirl
LunaCodeGirl

Reputation: 5630

If they're all like that I would use regex.

Upvotes: 0

Related Questions