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> </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.
jQuery can help you with that:
$("p").html(function(index, oldHtml) {
if (oldHtml === " ") {
$(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() === " ") {
$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()) == ' ')
{
$(this).remove();
}
}
You can also use the ":contains" selector to only get the paragraphs that contain a non-breaking space:
$('p:contains(" ")')
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();
}
});
If they're all like that I would use regex.
精彩评论