将DOM元素数组减少到JavaScript中最深层次的元素

编程入门 行业动态 更新时间:2024-10-26 06:36:46
本文介绍了将DOM元素数组减少到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中最深层次的元素

本文发布于:2023-10-30 07:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   数组   最深   层次   DOM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!