如何创建HTML DOM使用JavaScript的叶节点的数组 [英] How to create an array of leaf nodes of an html dom using javascript
问题描述
所以我的问题基本上是这样,我怎么能恢复使用JavaScript函数的HTML文档的所有叶子节点的数组。我以后需要该列表上执行操作。例如,如果我有HTML:
So my question is basically this, how can I return an array of all the leaf nodes of an html document using a javascript function. I need to perform operations on that list later. for example if I have html:
<body>
<div>
<div>
<p id="para1"></p>
</div>
</div>
<p id="para2"></p>
</body>
则函数应该返回含ID PARA1和PARA2两个节点的数组。
then the function should return a array containing the two nodes with id para1 and para2.
请注意:我想节点本身不是他们的ID。虽然给出的ID我可以提取节点所以它不是一个大问题。
Note: I want the nodes themselves not their id. Although given the id i can extract the nodes so its not a big issue.
推荐答案
下面是一个简单的函数来得到你看看所有节点叶节点,包括文本节点(这意味着它永远不会返回包含文本节点的元素)
Here's a simple function to get leafNodes where you look at all nodes, including text nodes (this means it won't ever return an element that contains text nodes):
function getLeafNodes(master) {
var nodes = Array.prototype.slice.call(master.getElementsByTagName("*"), 0);
var leafNodes = nodes.filter(function(elem) {
return !elem.hasChildNodes();
});
return leafNodes;
}
工作演示: http://jsfiddle.net/jfriend00/e9D5n/
仅供参考, .filter()
方法需要IE9。如果要使用此方法与早期版本的IE浏览器,你可以安装 .filter)一个填充工具(
或更改到阵列的手动迭代。
FYI, the .filter()
method requires IE9. If you want to use this method with earlier versions of IE, you can install a polyfill for .filter()
or change to a manual iteration of the array.
和,这里如果你不想考虑文本节点,所以你要找叶元素的版本,即使他们有他们的文本节点:
And, here's a version if you don't want to consider text nodes, so you're looking for the leaf elements, even if they have text nodes in them:
function getLeafNodes(master) {
var nodes = Array.prototype.slice.call(master.getElementsByTagName("*"), 0);
var leafNodes = nodes.filter(function(elem) {
if (elem.hasChildNodes()) {
// see if any of the child nodes are elements
for (var i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeType == 1) {
// there is a child element, so return false to not include
// this parent element
return false;
}
}
}
return true;
});
return leafNodes;
}
工作演示: http://jsfiddle.net/jfriend00/xu7rv/
和,这里忽略文本节点的递归解决方案:
And, here's a recursive solution that ignores text nodes:
function getLeafNodes(master) {
var results = [];
var children = master.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType == 1) {
var childLeafs = getLeafNodes(children[i]);
if (childLeafs.length) {
// if we had child leafs, then concat them onto our current results
results = results.concat(childLeafs);
} else {
// if we didn't have child leafs, then this must be a leaf
results.push(children[i]);
}
}
}
// if we didn't find any leaves at this level, then this must be a leaf
if (!results.length) {
results.push(master);
}
return results;
}
工作演示: http://jsfiddle.net/jfriend00/jNn8H/
这篇关于如何创建HTML DOM使用JavaScript的叶节点的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!