代码之家  ›  专栏  ›  技术社区  ›  klewis

jQuery查找准确的HTML内容

  •  0
  • klewis  · 技术社区  · 12 年前

    我使用以下脚本来查找父ID容器中符合窗帘标准的所有h1元素。。。

    $('#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>
    

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

    5 回复  |  直到 12 年前
        1
  •  2
  •   Mohammed R. El-Khoudary    12 年前

    如果要删除包含nbsp的所有h1,可以尝试以下操作: 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();
        }
    });
    
        2
  •  1
  •   domdomcodecode    12 年前

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

    $('#yourParent h1').each(function(){
        if($(this).html() == "&nbsp;"){
            // magic
        }
    });
    
        3
  •  0
  •   Vasil Dininski Nifras Nipy    12 年前

    我想你可以这样做:

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

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

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

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

        4
  •  0
  •   isherwood    12 年前
    var myRegEx = new RegExp('^&nbsp;\s');    
    
    $('#myDiv h1').each(function() {
        var myText = $(this).text();
    
        if (myText.match(myRegEx) ) { ... }
    });
    
        5
  •  0
  •   Saiqul Haq    12 年前

    您可以使用正则表达式过滤元素,如果没有任何值,则将其删除

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

    here a demo