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

← PrevNext →

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>
    <title>JavaScript hasChildNodes() example</title>
    	table, p { 
            font: 1em Calibri;
    <table id="mytable">
            <td><span style="color:red">t1</span></td>

    	<input type="button" value="Get child nodes of <td>'s" 
            onclick="getChildNode('mytable')" />
    <p id="msg"></p>
    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)


        document.getElementById("msg").innerHTML = 'Please see the console window for the result.';
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.

← PreviousNext →

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