2014-03-03 26 views
0

我使用下面的脚本找到所有H1元素,父ID容器,将适合帷幕标准之内...的jQuery找到准确的HTML内容

$('#cpcompheader h1').html(" ").remove(); 

该脚本找到任何情况下,如....

<h1>&nbsp;</h1> 
<h1>&nbsp; one two</h1> 
<h1>&nbsp; the sun is up</h1> 
<h1>&nbsp; etc...</h1> 

但我只是想找到的所有实例...

<h1>&nbsp;</h1> 

那么我们应该如何修改我的代码?谢谢!

回答

1

你可以尝试找到所有的h1标签,然后检查它们是否包含某个值。

$('#yourParent h1').each(function(){ 
    if($(this).html() == "&nbsp;"){ 
     // magic 
    } 
}); 
+0

为什么不在选择器中包含if检查?此外,当' '不是唯一的内容时,您的字符串将不匹配。你可能需要一个正则表达式。 – isherwood

+1

我想你可以在选择器中包含'if'语句。关于内容,我想他只是想抓住那些只匹配一个' ' – Coderchu

0

我想你可以这样做:

$('h1:contains(&nbsp;)'); 

,或者如果你想要的精确匹配:

$('h1').filter(function(index) { return $(this).text() === "&nbsp;"; }); 

你也可以看看包含选择文档:https://api.jquery.com/contains-selector/

+0

这将不匹配只包含指定的值,虽然,它包括任何H1的有 元素。这取决于OP想要的。 – Coderchu

+0

'包含()'查找HTML实体吗? – isherwood

+0

@isherwood我不这么认为。我已编辑的答案添加确切的字符串匹配:) –

2

如果你想删除包含NBSP所有H1S你可以尝试这样的事: removing all elements that contains nbsp

$("h1").each(function() { 
if ($(this).html().indexOf("&nbsp;") != -1) { 
    $(this).remove(); 
} 
}); 

现在,如果你想删除元素完全匹配的NBSP只是修改成这样的:modified version

$("h1").each(function() { 
    if ($(this).html() === "&nbsp;") { 
     $(this).remove(); 
    } 
}); 
0
var myRegEx = new RegExp('^&nbsp;\s');  

$('#myDiv h1').each(function() { 
    var myText = $(this).text(); 

    if (myText.match(myRegEx)) { ... } 
}); 
0

你可以过滤器使用正则表达式的元素,然后将其删除,如果不具有任何价值

$('h1').each(function(){ 
    var filtered = $(this).html($(this).html().replace(/&nbsp;/gi,''));  
    if($(filtered).html() === ''){ 
    $(filtered).remove(); 
    } 
}); 

here a demo