Check if div is descendant of another

// x is the element we are checking
while (x = x.parentNode) { 
    if (x.id == "a") console.log("FOUND");
}

If you want to use pure javascript use node.contains.

e.g.

var a = document.getElementById('a');
var d = document.getElementById('d')
if (a.contains(d)) {
    alert('d is a descendant of a');
}

Fiddle: http://jsfiddle.net/FlameTrap/pwVPC/


You can use node.contains to check if a node contains another node. https://developer.mozilla.org/en-US/docs/Web/API/Node.contains


The method closest() might also be useful in such cases. This method returns the closest ancestor element of an element that matches a given selector (e.g. a class or id). If there is no such element, the method returns null.

let d = document.getElementById("d");
// if there is no ancestor with the id 'a', the method returns null and this evaluates to false:
if(d.closest("#a")){
   alert("d is a descendant of an element with the id 'a'");
}

You can find further description and more usage examples on MDN.

Tags:

Javascript