Using jQuery to determine if an element is a child of another element

Posted by Dan on Sep 24, 2008 @ 9:50 AM

I seem to be writing a lot of code as of late that needs to check if a certain element is a child of another element. This is extremely useful in drag and drop operations (for determine where an element is being dropped) or if you want to make sure that a global event was trigger on a specific set of elements (I use this to check if a document.click occurred on a specific container.)

While jQuery makes this easy enough to do, I don't find the code very readable or reusable so I started using the following snippet:

jQuery.fn.isChildOf = function(b){
    return (this.parents(b).length >
0);
};

What this does is checks to see if the current element is a child of the specified selector. For example:

$("#list > li > a").isChildOf("#list"); // return true
$("#list > li > a").isChildOf("#list > li"); // return true
$("#list > li").isChildOf("#list > li > a"); // return false

This function definitely comes in handy when doing any sort of event delegation and I hope it eventually makes its way into the jQuery core in some form or another.

Categories: jQuery

9 Comments


Comments for this entry have been disabled.