0

我有一些示例网站,我想在整个文档和正文节点中显示子节点的数量。我设法使用代码来做到这一点:

   var childDoc = document.childNodes.length;
   alert("Document have " + childDoc + " child nodes");

   var childDoc2 = document.body.childNodes.length;
   alert("Body have " + childDoc2 + " child nodes");

现在我需要列出这些节点名称,但我不知道如何。谁能帮我?

编辑。工作解决方案

var bodyChilds = document.body.childNodes;
var strg = "";

for(var i=0; i < bodyChilds.length; i++){
strg = strg + bodyChilds[i].nodeName + "\n";
}

alert (strg);
4

2 回答 2

0

只需使用简单的循环和数组索引。您可以在此处阅读更多内容:ChildNodes

for (var i=0;i<document.body.childNodes.length;i++)
    { 
       //current node in childNodes[i]
    }
于 2013-10-01T10:47:34.577 回答
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);
于 2013-10-01T10:56:51.327 回答