hasChildNodes() Syntax
hasChildNodes()
The method takes no parameters. It returns a boolean "true" or "false". True, if element has a child node.
Example:
I have a table with 2 rows and few <td>’s (or cells). One of the cells (<td>) does not have a value and rest has a value.
<!DOCTYPE html>
<html>
<body>
<table id="mytable">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td><span style="color:red">t1</span></td>
<td></td>
</tr>
<tr>
<td>t2</td>
<td>Bravo</td>
</tr>
</table>
<p>
<input type="button" value="Get child nodes of <td>'s"
onclick="getChildNode('mytable')" />
</p>
<p id="msg"></p>
</body>
<script>
let getChildNode = (ele) => {
// get all <td>'s in the table.
let td = document.querySelectorAll("#" + ele + " td");
for (i = 0; i < td.length; i++) {
if (td[i].hasChildNodes() === true) { // Check if <td> has child nodes.
if (td[i].childNodes[0] !== undefined)
console.log(td[i].childNodes[0]);
// Output (returns 3 child nodes:
<span style="color:red">t1</span>
t2
Bravo
}
}
}
</script>
</html>In the script section, I have defined the hasChildNode() method inside an if condition.
if (td[i].hasChildNodes() === true) { }
Here's another example.
If you want you can remove a particular child node. All you have to do is, check if the parent element has the childs node(s) you want to remove.
<script>
let getChildNode = (ele) => {
// get all <td>'s in the table.
let td = document.querySelectorAll("#" + ele + " td");
for (i = 0; i < td.length; i++) {
// Check if a <td> has child nodes.
if (td[i].hasChildNodes() === true) {
if (td[i].childNodes[0].innerHTML === 't1') { // Check if child node has a particular value.
td[i].removeChild(td[i].childNodes[0]); // If yes, remove the node.
}
}
}
document.getElementById("msg").innerHTML = 'Child node removed';
}
</script>