How to check if <td>’s in a <table> has Child Nodes

A <td> element in an HTML table, defines a cell. Every <td> will have a value or data in it. It can hold different types of data, such as text, number, image and some time nothing at all. Now, how do you check at runtime if a <td> has a child node or any value? If you are using JavaScript, you can use the hasChildNodes() method to check if a <td> has child nodes.

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>
Try it

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.

Related Post: 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.

← Previous



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner