jQuery找到确切的HTML内容

我使用以下脚本在父ID容器中查找所有h1元素,这些元素将符合幕布标准…

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

该脚本正在寻找任何场景,例如….

 

 

  one two

  the sun is up

  etc...

但我只想找到……的所有实例

 

 

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

您可以尝试查找所有h1标签,然后检查它们是否包含特定值。

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

如果您要删除包含所有内容的h1,可以尝试以下操作: 删除包含nbsp的所有元素

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

现在,如果您要删除完全匹配的元素,只需将其修改为: 修改后的版本

 $("h1").each(function() { if ($(this).html() === " ") { $(this).remove(); } }); 

我猜你可以这样做:

 $('h1:contains( )'); 

或者如果你想要完全匹配:

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

您还可以查看包含选择器文档: https : //api.jquery.com/contains-selector/

 var myRegEx = new RegExp('^ \s'); $('#myDiv h1').each(function() { var myText = $(this).text(); if (myText.match(myRegEx) ) { ... } }); 

您可以使用正则表达式过滤元素,然后在没有任何值的情况下将其删除

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

这是一个演示