【问题标题】:Get comment nodes in DOM deep level获取 DOM 深层次的评论节点
【发布时间】:2015-11-05 02:46:50
【问题描述】:

如何获取包含 DOM 中所有注释元素的数组或类数组(JQuery 对象)? JQuery contents() 只检索 1 级元素。

更广泛的问题:我需要删除 DOM 中 2 个文本 cmets 之间的所有元素。评论也可以在子元素中。

...html code...
<!--remove from here-->
...code...
<!--finish removing-->
...html code...

所以在方法之后,HTML DOM 应该是这样的:

...html code...
...html code...

谢谢。

【问题讨论】:

    标签: javascript jquery dom-manipulation


    【解决方案1】:

    您可以使用TreeWalker 并将whatToShow 设置为NodeFilter.SHOW_ALL 来查看文档上的所有节点。

    var treeWalker = document.createTreeWalker(
      document.body,
      NodeFilter.SHOW_ALL,
      null,
      false
    );
    
    var commentList = [];
    
    while (treeWalker.nextNode()){
      // keep only comments
      if (treeWalker.currentNode.nodeType === 8) 
        commentList.push(treeWalker.currentNode);
    }
    
    var node;
    while (node !== commentList[1]) {
      node = commentList[0].nextSibling;
      node.parentElement.removeChild(node);
    }
    <!--Folowing element will be deleted-->
    <span> Hello world</span>
    <!-- the next one should be kept -->
    <span> keep me !</span>

    【讨论】:

    • 删除部分仅适用于给定的结构:如果只有两个 cmets,则删除两个 cmets 之间的所有内容。您可能需要检查这些是否是好的。
    • 我承认我还没有听说过 :) 我看到它很好地支持跨浏览器,所以很好。它比使用 RegEx 从 innerHtml 中删除文本更有效吗?非常感谢!
    • 效率更高是的!见this piece of history。还有,TreeWalker真的很强大,一定要试试。
    • 顺便说一句 - 对我来说更好的是使用过滤器:“SHOW_COMMENT”并删除目标评论的 nextSibling 直到下一个目标评论 ||空。
    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2011-12-05
    • 2012-08-12
    • 1970-01-01
    • 2016-03-21
    • 2022-07-28
    • 2013-06-20
    相关资源
    最近更新 更多