Best way to find out if element is a descendant of another

In jQuery 1.6, you can use the following code generically, e.g. targetElt and parentElt can both be DOM elements or jQuery-wrapped objects, as well as selectors:

$(targetElt).closest(parentElt).length > 0

Some of the other answers require you to refer to elements by their IDs, which isn't useful if all you have is a DOM element without an ID. Also, if you want to make sure that the targetElt is a strict descendant of parentElt (in other words, you don't want to count parentElt as its own descendant), make sure to add a targetElt != parentElt check before your call to .closest(), or use .parents().find() as Jonathan Sampson suggests.


JQuery

With jQuery >=1.4 (2010) you can use the very fast function jQuery.contains()

This static method works with DOM elements, not with jQuery elements and returns true or false.

jQuery.contains( container, descendant )

Example: To check if a element is in the document you could do this:

jQuery.contains( document.body, myElement )

Native DOM

There is also a native DOM method Node.contains() that all browsers since ie5+ supports. So you can do it without jQuery:

document.body.contains( myElement )

Tags:

Jquery