如何使用 JavaScript 检查元素是否是父元素的子元素?
- 方法一:使用 Node.contains() 方法
Node.contains()方法用于检查给定节点是否是任何级别的另一个节点的后代。后代可能直接是孩子的父母,也可能是更上一层。它返回结果的布尔值。该方法用于父元素,方法中传入的参数是要检查的子元素。如果孩子是父母的后代,则返回true。这意味着该元素是父元素的子元素。
句法:
function checkParent(parent, child) { if (parent.contains(child)) return true; return false; }
例子:
How to Check if an element is a child of a parent using JavaScript? GeeksforGeeks
How to Check if an element is a child of a parent using JavaScript?This is the parent div.This is the child div.This is outside the parent div.Click on the button to check if the elements are child of a parent.
Child has parent:
Non-Child has parent:
输出:
- 在点击按钮之前:
- 点击按钮后:
- 在点击按钮之前:
- 方法2:遍历给定孩子的父母
可以通过一个接一个地不断循环元素的父项来检查子项是否具有给定的父项。通过访问parentNode属性找到每个节点的父节点,该属性返回父节点(如果有)。使用 while 循环,直到找到所需的父元素或不再存在父元素。在这个循环中,每个元素的父节点都会在每次迭代中找到。如果父节点在任何迭代中与给定的节点匹配,则意味着该元素是父节点的子节点。
句法:
function checkParent(parent, child) { let node = child.parentNode; // keep iterating unless null while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }
例子:
How to Check if an element is a child of a parent using JavaScript? GeeksforGeeks
How to Check if an element is a child of a parent using JavaScript?This is the parent div.This is the child div.This is outside the parent div.Click on the button to check if the elements are child of a parent.
Child has parent:
Non-Child has parent:
输出:
- 在点击按钮之前:
- 点击按钮后:
- 在点击按钮之前: