这是一个简单的函数来获取leafNodes,您可以在其中查看所有节点,包括文本节点(这意味着它永远不会返回包含文本节点的元素):
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() 安装 polyfill 或更改为数组的手动迭代。
如果您不想考虑文本节点,这里有一个版本,因此您正在寻找叶元素,即使它们中有文本节点:
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/
还有,这是一个忽略文本节点的递归解决方案:
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/