代码之家  ›  专栏  ›  技术社区  ›  Steve Perks

如何使用jQuery识别可能包含注释标记的空元素?

  •  1
  • Steve Perks  · 技术社区  · 16 年前

    我试图识别一个空元素,该元素可能包含或不包含注释标记和/或空白。

    以下HTML结构在我使用的环境中很常见:

    <div class="container container-no-title">
      <div id="dnn_ctr6735_ContentPane" class="container-padding DNNAlignright">
        <!-- Start_Module_6735 -->
        <div id="dnn_ctr6735_ModuleContent">
          <!-- End_Module_6735 -->
        </div>
      </div>
    </div>
    

    $('.container-padding > div').each(function() {
      if ($(this).is(":empty")) {
        $(this).parent('.container-padding').remove();
      };
    });
    

    但这不包括空格或注释标记。我还发现了其他一些涉及空白的问题,但没有任何涉及注释标记的问题,我真的很想让jQuery的这个小片段保持简单。

    史蒂夫

    4 回复  |  直到 16 年前
        1
  •  4
  •   tvanfosson    16 年前

    您是否尝试过:

    $('.container-padding > div').each(function() {
        if ($(this).text().match(/^\s*$/)) {
            $(this).parent('.container-padding').remove();
        }
    });
    

    甚至

    $('.container-padding').each( function() {
        if ($(this).text().match(/^\s*$/)) {
            $(this).remove();
        }
    });
    
        2
  •  1
  •   Brett Pontarelli    16 年前

    如果我理解正确,空元素应该没有子元素:

    $(this).children().length == 0

        3
  •  1
  •   Omer Bokhari    16 年前

    很高兴电视的解决方案对你有用。您还可以使用直接向上的DOM通过检查nodeType值来查找不是“元素”的节点。

    例如,在element.childNodes上迭代:

    if (element.childNodes[i].nodeType != 1)
    // node is not an element (text/whitespace or comment)
    

    或:

    if (element.childNodes[i].nodeType == 8)
    // node is a comment
    

    检查 here

        4
  •  0
  •   Darin Dimitrov    16 年前