如果我有那个
<!-- some comment -->
如何获取此元素并使用javascript更改内容? 如果我有一个代码,我想删除评论标记,我该怎么办?
答案 0 :(得分:27)
最好的方法是使用专用的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));
});
如果您必须支持较旧的浏览器(例如IE&lt; 9),您需要自己遍历DOM并提取node type为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)
答案 1 :(得分:4)
你必须遍历DOM才能获得它。
注释DOM元素的nodeType
为8
if( oNode.nodeType === 8 ) {
oNode.parentNode.removeChild( oNode );
}
将是一种方法
答案 2 :(得分:0)
这是一个检索评论的JQuery插件:
基本想法是查看nodes
,而不是elements
:
http://www.w3schools.com/htmldom/dom_nodes.asp
您从document
对象开始,并使用childNodes
集合迭代它们。您必须检查node.nodeType == 8
,它将仅返回注释节点(请注意,您需要递归迭代子节点)。
答案 3 :(得分:0)
我需要存储整个网页的模板。但是标签不能包含例如标签。因此,我决定将模板存储在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 <div>-tag is immediately followed by the "<!--", like this "<div><!--". 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>