I\'m trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.
I\'ve seen a model of testing
In jQuery ancestors using jQuery objects I suggested
if ($(obj1).parents().index($(obj2)) >= 0) {
// obj1 is a descendant of obj2
}
a.contains(b)
This is a pure JavaScript solution using Node.contains. The function is inclusive, a.contains(a)
evaluates to true.
There's an edge case in IE9: if b
is a text node, contains
will always return false.
Try this:
$('#foo').filter(function(){
return $(this).parent().is('#foo-parent');
});
So here we are selecting all the foo elements and then filtering only the elements that have the foo-parent as their immediate parent.
If you are looking to find if the any of the ancestors of the current object comply to the rule, then I guess it should be:
$('#foo').filter(function(){
return $(this).parents().is('#foo-parent');
});