Here’s an example.
<!DOCTYPE html> <html> <head> <title>JavaScript hasChildNodes() example</title> <style> table, p { font: 1em Calibri; } </style> </head> <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++) { // Check if a <td> has child nodes. if (td[i].hasChildNodes() === true) { if (td[i].childNodes[0] !== undefined) console.log(td[i].childNodes[0]); } } document.getElementById("msg").innerHTML = 'Please see the console window for the result.'; } </script> </html>
In the markup section above, I have a table with 2 rows and few <td>’s (or cells). One the cell or <td> does not have a value and rest has a value.
How getElementById Method works in JavaScript
Now, in the script section, I have defined the hasChildNode() method inside an if condition.
The JavaScript hadChildNode() method returns a Boolean value (true or false). Therefore, if a td has a value (or a child node) the method will return a true or else false. The output of the above script will be 3 child nodes.
Thanks for reading. ☺