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>
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]
How can i do this?
By the way: “Deepest elements” seems to be the wrong term for what i am trying to do. Is there any better name?
I found a working solution (JQuery distinct descendants (filter out all parents in result set)).
Code credits to cfedermann: