How to check in Javascript if one element is contained within another

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:

if (element1.hasDescendant(element2))


if (element2.hasParent(element1))

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


Another solution that wasn’t mentioned:

Example Here

var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
  // .. it's a child

It doesn’t matter whether the element is a direct child, it will work at any depth.

Alternatively, using the .contains() method:

Example Here

var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
  // .. it's a child