簡體   English   中英

如何使用 javascript 獲取 HTML 注釋

[英]How do I get an HTML comment with javascript

如果我有那個

  <!-- some comment -->

如何獲取此元素並使用 javascript 更改內容? 如果我有一個代碼,我想刪除評論標簽,我該怎么做?

使用 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)

你必須遍歷 DOM 才能得到它。 評論DOM元素的nodeType8

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

將是一種方法

這是一個檢索評論的 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它將只返回注釋節點(請注意,您需要遞歸遍歷子節點)。

我需要為整個網頁存儲一個模板。 但是 <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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM