How to check in Javascript if one element is contained within another
02:54 10 Feb 2010

How can I check if one DOM element is a child of another DOM element? Are there any built in methods for this?

For example, something like this to check if element2 is contained within element1:

if (element1.hasDescendant(element2)) 

Or if element2 has element1 as a parent/grandparent/etc:

if (element2.hasAncestor(element1)) 

If not then any ideas how to do this? It also needs to be cross-browser compatible. I should also mention that the child could be nested many levels below the parent.

javascript dom