views:

1575

answers:

2

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 for

$b.parents('nodename').length>0

Which is fantastic when you only need to check if an element is a child of any node by that name.

But what about a specific node? You can't test

$b.parents($a).length>0

Because jQuery parents takes a nodename expression as an argument to filter.

As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.

Thanks!

+2  A: 

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');

});
picardo
+5  A: 

In http://stackoverflow.com/questions/245241/jquery-ancestors-using-jquery-objects#245266 I suggested

if ($(obj1).parents().index($(obj2)) >= 0) {
    // obj1 is a descendant of obj2
}
Gareth
Perfect. This one actually allows the passing of an object instead of selector which is fantastic. Thanks again!
dreisch
You can pass an unwrapped DOM element to index, so this could be simplified to if ($(obj1).parents().index(obj2) >= 0)
Tim Moore