How to use the hasChildNodes() method In Javascript
The HTML hasChildNodes() property will return true if the given node has a child node or false if it doesn’t have any child nodes. A blank line or whitespace is also treated as a child node so it also returns true on a blank line or whitespace.
Example: This example shows the implementation of the above-explained approach.
HTML
<!DOCTYPE html> < html > < body > <!--In this example we will create a node of the type div and a button which calls a function name "exampleFunction" on clicking of this button it will show the properties of hasChildNode property --> < p id = "divId" ></ p > < br > < button onclick = "exampleFunction()" > click to know the paragraph tag has any child node </ button > <!-- below paragraph Tag is used to print the value of nodeValue properties--> < p id = "w3wiki" ></ p > < script > // utility function to demonstrate hasChildNode Property function exampleFunction() { // let x used to get the information of those node // for which you want to perform // hasChildNode properties let res = document.getElementById("divId").hasChildNodes(); document.getElementById("w3wiki" ).innerHTML = res; } </ 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