我有一些示例网站,我想在整个文档和正文节点中显示子节点的数量。 我设法使用代码来完成它:
var childDoc = document.childNodes.length;
alert("Document have " + childDoc + " child nodes");
var childDoc2 = document.body.childNodes.length;
alert("Body have " + childDoc2 + " child nodes");
现在我需要列出那些节点名称,但我不知道如何。任何人都可以帮助我吗?
EDIT。 工作解决方案
var bodyChilds = document.body.childNodes;
var strg = "";
for(var i=0; i < bodyChilds.length; i++){
strg = strg + bodyChilds[i].nodeName + "\n";
}
alert (strg);
答案 0 :(得分:0)
只需使用简单的循环和数组索引。 您可以在此处阅读更多内容:ChildNodes
for (var i=0;i<document.body.childNodes.length;i++)
{
//current node in childNodes[i]
}
答案 1 :(得分:0)
获取每个孩子(标签)名称
var bodyChilds = document.body.childNodes;
var tagNames = [];
var localNames = [];
var nodeNames = [];
for(var i=0; i<bodyChilds.length; i++){
// note: tag name will be undefined when is a text node
//Here you can check null/undefined and take decision according to your need
tagNames.push(bodyChilds[i].tagName);
localNames.push(bodyChilds[i].localName) //Name provided by developer in html
nodeNames.push(bodyChilds[i].nodeName)
}
console.log(tagNames);
console.log(localNames);
console.log(nodeNames);