I needed a method to filter out all elements that are parents of other elements in the result set. I tried to write a plugin:
jQuery.fn.distinctDescendants = function() {
var nodes = [];
var result = this;
jQuery(result).each(function() {
var node = jQuery(this).get(0);
if(jQuery(node).find(result).length == 0) {
nodes.push(node);
}
});
return nodes;
};
When i run the following command on this example page:
jQuery('body, textarea').distinctDescendants();
I get the (wrong) result:
[body.contact-page, textarea, textarea]
This is wrong because body is the parent of at least one other element in the result (both textareas). Therefore the expected result would be:
[textarea, textarea]
What is wrong here?
Why aren’t you using
jQuery('body > input')instead?You can use the following (verbose) code to achieve what you want; it should work as drop-in replacement of your plugin code.