Looping through the parents of the given child
The child can be checked to have the given parent by continuously looping through the element’s parents one by one. The parent of each node is found by accessing the parentNode property which returns the parent node if any. A while loop is used until the parent required is found or no more parent elements exist. Inside this loop, each element’s parent node is found in every iteration. If the parent node matches the given one in any iteration, it means that the element is a child of the parent.
Syntax:
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;
}
Example: This example shows the implementation of the above-explained approach.
html
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < title >Document</ title > < style > .parent, .child, .non-child { border: 2px solid; padding: 5px; margin: 5px; } </ style > </ head > < body > < h1 style = "color: green" >w3wiki</ h1 > < b > How to Check if an element is a child of a parent using JavaScript? </ b > < div class = "parent" >This is the parent div. < div class = "child" >This is the child div. </ div > </ div > < div class = "non-child" > This is outside the parent div. </ div > < p >Click on the button to check if the elements are child of a parent.</ p > < p >Child has parent: < span class = "output-child" ></ span > </ p > < p >Non-Child has parent: < span class = "output-non-child" ></ span > </ p > < button onclick = "checkElements()" > Check elements </ button > < script > 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; } function checkElements() { parent = document.querySelector('.parent'); child = document.querySelector('.child'); non_child = document.querySelector('.non-child'); output_child = checkParent(parent, child); output_non_child = checkParent(parent, non_child); document.querySelector('.output-child').textContent = output_child; document.querySelector('.output-non-child').textContent = output_non_child; } </ script > </ body > </ html > |
Output:
How to Check if an element is a child of a parent using JavaScript?
In this article, we are going to see the methods by which we can Check if an element is a child of a parent using JavaScript.
These are the following methods:
Table of Content
- Using the Node.contains() method
- Looping through the parents of the given child
- Using the hasChildNodes() method