HTML如何获取comment(注释)元素对象?
获取普通的元素可以用document.getElementById(id),但是注释元素既没有名字也没有ID该怎么获取呢?...
获取普通的元素可以用document.getElementById(id),但是注释元素既没有名字也没有ID该怎么获取呢?
展开
2016-05-26 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
参考:
// ie9以前
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;
}
ie9以后:
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));
});
// ie9以前
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;
}
ie9以后:
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));
});
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询