开发者

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

开发者 https://www.devze.com 2023-01-31 00:05 出处:网络
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 t

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.


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.


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;")')


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();
  }
});


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

0

精彩评论

暂无评论...
验证码 换一张
取 消