假设我们要查明该
child
元素是否是该元素的后代parent
。1.使用包含方法
const isDescendant = parent.contains(child)
2. 从子元素上去,直到见到父级
// Check if `child` is a descendant of `parent`
const isDescendant = function (parent, child) {
let node = child.parentNode;
while (node) {
if (node === parent) {
return true;
}
// Traverse up to the parent
node = node.parentNode;
}
// Go up until the root but couldn't find the `parent`
return false;
};