30

如果我有那个

  <!-- some comment -->

如何获取此元素并使用 javascript 更改内容?如果我里面有一个代码,我想删除评论的标签,我该怎么做?

4

4 回答 4

31

使用 NodeIterator (IE >= 9)

最好的方法是使用一个专用的NodeIterator实例迭代给定根元素中包含的所有注释。

在行动中看到它!

function filterNone() {
    return NodeFilter.FILTER_ACCEPT;
}

function getAllComments(rootElem) {
    var comments = [];
    // Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11
    var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false);
    var curNode;
    while (curNode = iterator.nextNode()) {
        comments.push(curNode.nodeValue);
    }
    return comments;
}

window.addEventListener("load", function() {
    console.log(getAllComments(document.body));
});

使用定制的 DOM 遍历(也支持 IE < 9)

如果你必须支持旧的浏览器(例如IE <9),你需要自己遍历DOM并提取节点类型为的元素Node.COMMENT_NODE

在行动中看到它!

// Thanks to Yoshi for the hint!
// Polyfill for IE < 9
if (!Node) {
    var Node = {};
}
if (!Node.COMMENT_NODE) {
    // numeric value according to the DOM spec
    Node.COMMENT_NODE = 8;
}

function getComments(elem) {
  var children = elem.childNodes;
  var comments = [];

  for (var i=0, len=children.length; i<len; i++) {
    if (children[i].nodeType == Node.COMMENT_NODE) {
      comments.push(children[i]);
    }
  }
  return comments;
}

提取节点的内容并将其删除

与您从上面选择的方式无关,您会收到相同的节点 DOM 对象。

访问评论的内容就像commentObject.nodeValue.
删除评论有点冗长:commentObject.parentNode.removeChild(commentObject)

于 2012-11-13T15:56:09.713 回答
5

你必须遍历 DOM 才能得到它。nodeType评论 DOM 元素的8

if( oNode.nodeType === 8 ) {
  oNode.parentNode.removeChild( oNode );
}

将是一种方法

于 2012-11-13T15:54:19.327 回答
1

这是一个检索评论的 JQuery 插件:

http://www.bennadel.com/blog/1563-jQuery-Comments-Plug-in-To-Access-HTML-Comments-For-DOM-Templating.htm

基本思想是看nodes,而不是elements

http://www.w3schools.com/htmldom/dom_nodes.asp

您从对象开始,并使用集合document遍历它们。childNodes您必须检查node.nodeType == 8哪个将仅返回注释节点(请注意,您需要递归地遍历子节点)。

于 2012-11-13T15:53:40.657 回答
0

我需要为整个网页存储一个模板。但是 <template>-tag 不能包含例如 <html>-tag。所以我决定将我的模板存储在 HTML 注释中。

我将 HTML 注释放在隐藏的 <div> 中,以便更轻松地检索该特定 HTML 注释中的文本,而不必费心将其与其他 HTML 注释区分开来。

这是一个演示如何使用 createTreeWalker 检索 HTML 注释中的内容。

alert(
  document.createTreeWalker(
    document.getElementById('commentDiv'), 
    NodeFilter.SHOW_COMMENT, 
    null, 
    false
  ).nextNode().nodeValue
);
<p>Getting the text in a HTML-comment.</p>
<p>I use createTreeWalker to make sure we don't simply capture an empty text node by mistake. You could make the code even simpler, but then you must make sure that the &lt;div>-tag is immediately followed by the "&lt;!--", like this "&lt;div>&lt;!--". But if that breaks because of for example autoformating in an editor, so that you get a line feed in between or so, then the simpler method will fail. That is why I prefere to use the createTreeWalker here.</p>
<!--
  This is NOT the comment we want to get text from
-->
<div id="commentDiv" style="display:none;">
  <!--
    This is THE text, and you can have anything in here
    <>
    <div>
    <script>alert('hello');</script>
    etc.
    except of course an end of HTML-comment.

    An advantage of this way to store a template compared to using
    the <template>-tag, is that the <template>-tag can for example
    not contain a <html>-tag, in case you need to have a template
    for an entire web page.

    Check also my explanation down in the body text for why I use 
    createTreeWalker instead of some simpler code.
  -->
</div>
<!--
  This is also NOT the comment we want to get text from
-->
<p>End of body.</p>

于 2020-08-15T16:39:29.683 回答