Tuesday, July 15, 2008

jQuery isChildOf - is element a child of / ancestor of element - plugin

If anyone knows of an existing jQuery method of determining whether an element is a child of another element, please feel free to post. I couldn't find one, so I developed the plugin below:


(function($) {
$.fn.extend({
isChildOf: function( filter_string ) {

var parents = $(this).parents().get();

for ( j = 0; j < parents.length; j++ ) {
if ( $(parents[j]).is(filter_string) ) {
return true;
}
}

return false;
}
});
})(jQuery);


The usage is:

$(element).isChildOf(filter_string)

where filter_string is any of the expr values that can be passed to JQuery's is() function. You can get more information here

example:

<div id="parent2">
<div id="parent1">
<div id="child">
</div>
</div>
</div>


Alerts "true":

alert( $('#child').isChildOf('#parent1') );

Alerts "true":

alert( $('#child').isChildOf('#parent2') );

Alerts "false"

alert( $('#child').isChildOf('#notaparent') );

8 comments:

Unknown said...

Nice code, byt why not simply extend selectors ? ;)

http://ejohn.org/blog/qualified-selectors-in-jquery/

Anonymous said...

-
Hi,

Shouldn't it be enough to check for

if (parents.length > 0)

in your code without the need to run throug the for loop?

djot
-

Jim Keller said...

>Nice code, byt why not simply extend selectors ? ;)

I worked with selectors a bit and couldn't come up with anything that would accomplish what I Was looking for. I wanted to close a popup window if anywhere *other* than the window (or its children) were clicked, and I couldn't come up with a selector that would let me say "is the element that triggered the event a child, direct or indirect, of x container?". It's quite possible I'm just not well versed enough in selectors to know the syntax, but I've yet to come across it.

>Shouldn't it be enough to check for
>if (parents.length > 0)

I needed to check whether the element was a descendant of the given parent, not just a direct descendant, so I needed to go through the loop until all parents were exhausted.

kazhar said...

er... parents().filter(expr) ?

Unknown said...

This should work too:

$("#child").parents().is("#parent")

Digstarian said...

how about...

$.fn.isChildOf = function(exp){
return $(child).parents().filter(exp).length>0;
};

Wow Gold said...

WOW GOLD from randyrun. Most cheapest wow gold supplier.More than 10,000 online satisfied customers bears to the fact that we are genuine and fastest wowgold provider!

Nollan said...

This is a very helpful jQuery plugin!