如果我有
<!-- some comment -->
Run Code Online (Sandbox Code Playgroud)
如何获取此元素并使用javascript更改内容?如果我有一个代码,我想删除评论标记我该怎么办?
Com*_*eek 28
最好的方法是使用专用的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));
});
Run Code Online (Sandbox Code Playgroud)
如果必须支持旧浏览器(例如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;
}
Run Code Online (Sandbox Code Playgroud)
独立于您从上面选择的方式,您将收到相同的节点DOM对象.
访问评论的内容非常简单commentObject.nodeValue
.
删除评论有点冗长:commentObject.parentNode.removeChild(commentObject)
您必须遍历DOM才能获得它。该nodeType
评论DOM元素是8
if( oNode.nodeType === 8 ) {
oNode.parentNode.removeChild( oNode );
}
Run Code Online (Sandbox Code Playgroud)
将是一种方法