将DOM元素数组减少到JavaScript中最深层次的元素 [英] Reduce array of DOM elements to the ones with the deepest level in JavaScript
问题描述
我们假设我有这样的HTML标记:
Let's assume i have HTML markup like this:
<body>
<div id="content">
<div id="sidebar">
</div>
<div id="main">
<p class="foo">text</p>
<p class="bar">more <span>text</span></p>
</div>
</div>
</body>
让我们进一步假设我在DOM元素数组中选择了其中一些:
Let's further assume that i selected some of them in an array of DOM elements:
var allElements = jQuery('div,p').get();
// result: [div#content, div#sidebar, div#main, p.foo, p.bar]
现在我想有效地从结果集中删除结果中包含子项的所有元素。换句话说,只有最深层次才能保留。因此,期望的结果是:
Now i want to efficiently remove all elements from the result set which have a child in the result. In other words, only the deepest level should remain. So, the desired result would be:
var deepestElements = doSomethingWith(allElements);
// desired result: [div#sidebar, p.foo, p.bar]
我该怎么做?
顺便说一下:最深的元素似乎是我想要做的错误术语。有没有更好的名字?
By the way: "Deepest elements" seems to be the wrong term for what i am trying to do. Is there any better name?
推荐答案
我找到了一个有效的解决方案( JQuery不同的后代(过滤掉结果集中的所有父项))。
I found a working solution (JQuery distinct descendants (filter out all parents in result set)).
代码信用cfedermann :
jQuery.fn.distinctDescendants = function() {
var nodes = [];
var parents = [];
// First, copy over all matched elements to nodes.
jQuery(this).each(function(index, Element) {
nodes.push(Element);
});
// Then, for each of these nodes, check if it is parent to some element.
for (var i=0; i<nodes.length; i++) {
var node_to_check = nodes[i];
jQuery(this).each(function(index, Element) {
// Skip self comparisons.
if (Element == node_to_check) {
return;
}
// Use .tagName to allow .find() to work properly.
if((jQuery(node_to_check).find(Element.tagName).length > 0)) {
if (parents.indexOf(node_to_check) < 0) {
parents.push(node_to_check);
}
}
});
}
// Finally, construct the result.
var result = [];
for (var i=0; i<nodes.length; i++) {
var node_to_check = nodes[i];
if (parents.indexOf(node_to_check) < 0) {
result.push(node_to_check);
}
}
return result;
};
这篇关于将DOM元素数组减少到JavaScript中最深层次的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!