tags:

views:

124

answers:

1

Hello,

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.hasChild(element2)) 

or

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.

Thanks,

AJ

+7  A: 

Using the parentNode property should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:

if (element2.parentNode == element1) { ... }

If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:

function isDescendant(parent, child) {
     var node = child.parentNode;
     while (node != null) {
         if (node == parent) {
             return true;
         }
         node = node.parentNode;
     }
     return false;
}
Asaph
Thanks for your reply, the problem is that the child could be nested many levels below the parent.
AJ
@AJ: I updated my answer to include a solution that should work for nesting the child arbitrarily deep in the parent.
Asaph
Thanks that looks exactly like what I need.
AJ