AJ.
AJ.

Reputation: 11240

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 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.

Upvotes: 325

Views: 286605

Answers (11)

Brian Di Palma
Brian Di Palma

Reputation: 7497

You should use Node.contains, since it's now standard and available in all browsers.

https://developer.mozilla.org/en-US/docs/Web/API/Node.contains

const parent = document.getElementById("my-parent")
const child = document.getElementById("my-child")
parent.contains(child)

an example of a "hasParent" function that would return if any elements are a parent:

const hasParent = (element, ...parents) => parents.some((parent) => parent.contains(element))

hasParent(child, parent1, parent2, parent3)

Upvotes: 479

Ben Carp
Ben Carp

Reputation: 26548

Via selector

A use case I had to work with isn't checking if an element is child of another specific element, but if an element is a child of a kind of element expressed by a selector. In such a case nowadays we can use Element.matches. Here is an example for a use case.

document.addEventListener("click", (ev)=>{
    if(ev.target.matches(".kind-of-el *")){
        console.log("click within 'kind-of-el'") 
    }
    
})

The other direction should also be possible in modern browsers. So to answer if an element has children with class 'kind-of-el' we can just check

if(el.matches(":has(.kind-of-el)")){
    console.log("el has a descendant with class 'kind-of-elzz'")
}

Upvotes: 2

helmax
helmax

Reputation: 71

Consider using closest('.selector')

It returns null if neither element nor any of its ancestors matches the selector. Alternatively returns the element which was found

Upvotes: 7

eljefedelrodeodeljefe
eljefedelrodeodeljefe

Reputation: 6791

TL;DR: a library

I advise using something like dom-helpers, written by the react team as a regular JS lib.

In their contains implementation you will see a Node#contains based implementation with a Node#compareDocumentPosition fallback.

Support for very old browsers e.g. IE <9 would not be given, which I find acceptable.

This answer incorporates the above ones, however I would advise against looping yourself.

Upvotes: 0

Asaph
Asaph

Reputation: 162791

Update: There's now a native way to achieve this. Node.contains(). Mentioned in comment and below answers as well.

Old answer:

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;
}

Upvotes: 312

RashFlash
RashFlash

Reputation: 1002

I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.

Below is the function:

function isChildOf(childObject, containerObject) {
  var returnValue = false;
  var currentObject;

  if (typeof containerObject === 'string') {
    containerObject = document.getElementById(containerObject);
  }
  if (typeof childObject === 'string') {
    childObject = document.getElementById(childObject);
  }

  currentObject = childObject.parentNode;

  while (currentObject !== undefined) {
    if (currentObject === document.body) {
      break;
    }

    if (currentObject.id == containerObject.id) {
      returnValue = true;
      break;
    }

    // Move up the hierarchy
    currentObject = currentObject.parentNode;
  }

  return returnValue;
}

Upvotes: 3

user3675072
user3675072

Reputation: 11

try this one:

x = document.getElementById("td35");
if (x.childElementCount > 0) {
    x = document.getElementById("LastRow");
    x.style.display = "block";
}
else {
    x = document.getElementById("LastRow");
    x.style.display = "none";
}

Upvotes: 1

Iegor Kozakov
Iegor Kozakov

Reputation: 361

You can use the contains method

var result = parent.contains(child);

or you can try to use compareDocumentPosition()

var result = nodeA.compareDocumentPosition(nodeB);

The last one is more powerful: it return a bitmask as result.

Upvotes: 26

Josh Crozier
Josh Crozier

Reputation: 240918

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
}

Upvotes: 33

GitaarLAB
GitaarLAB

Reputation: 14645

I just had to share 'mine'.

Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.

function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
  while((c=c.parentNode)&&c!==p); 
  return !!c; 
}

..or as one-liner (just 64 chars!):

function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}

and jsfiddle here.


Usage:
childOf(child, parent) returns boolean true|false.

Explanation:
while evaluates as long as the while-condition evaluates to true.
The && (AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand).

The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNode of c to c and then the AND operator will evaluate the resulting c as a boolean.
Since parentNode returns null if there is no parent left and null is converted to false, the while-loop will correctly stop when there are no more parents.

The right-hand side (of &&) is: c!==p.
The !== comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent is the parent then it evaluates to false.
So if c!==p evaluates to false, then the && operator returns false as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ; semicolon is required.)

So when the while-loop ends, c is either a node (not null) when it found a parent OR it is null (when the loop ran through to the end without finding a match).

Thus we simply return that fact (converted as boolean value, instead of the node) with: return !!c;: the ! (NOT operator) inverts a boolean value (true becomes false and vice-versa).
!c converts c (node or null) to a boolean before it can invert that value. So adding a second ! (!!c) converts this false back to true (which is why a double !! is often used to 'convert anything to boolean').


Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:

var a=document.getElementById('child'),
    b=document.getElementById('parent'),
    c;

c=a; while((c=c.parentNode)&&c!==b); //c=!!c;

if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
    //do stuff
}

instead of:

var a=document.getElementById('child'),
    b=document.getElementById('parent'),
    c;

function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}

c=childOf(a, b);    

if(c){ 
    //do stuff
}

Upvotes: 50

user663031
user663031

Reputation:

Take a look at Node#compareDocumentPosition.

function isDescendant(ancestor,descendant){
    return ancestor.compareDocumentPosition(descendant) & 
        Node.DOCUMENT_POSITION_CONTAINS;
}

function isAncestor(descendant,ancestor){
    return descendant.compareDocumentPosition(ancestor) & 
        Node.DOCUMENT_POSITION_CONTAINED_BY;
}

Other relationships include DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, and DOCUMENT_POSITION_FOLLOWING.

Not supported in IE<=8.

Upvotes: 23

Related Questions