How to check a table is empty or not using javascript

Phạm Trí picture Phạm Trí · Oct 30, 2018 · Viewed 8.7k times · Source

So i have a script like this to make a 2x2 table by javascript

function createtable(){
          var tbl = document.getElementById('x');
            if (tbl.contains()==false){
              tbl.setAttribute('border', '1');
              var tbdy = document.createElement('tbody');
              for (var i = 0; i < 2; i++) {
                var tr = document.createElement('tr');
                for (var j = 0; j < 2; j++) {         
                    var td = document.createElement('td');
                    tr.appendChild(td);
                    td.style.height='50px';
                    td.style.width='50px';
                }
                tbdy.appendChild(tr);
              }
              tbl.appendChild(tbdy);
        }

<form>
    <input type="button" value="Create Table" onclick="createtable()"> <br>
</form>
<table id="x"> </table>

I want to check if table x contains anything or not to create itself. Im trying to use the contains() to check but it doesnt work.

Answer

DDan picture DDan · Oct 30, 2018

You can check the number of rows in the table:

var x = document.getElementById("myTable").rows.length;

See reference here: https://www.w3schools.com/jsref/coll_table_rows.asp

Using this:

var tbl = document.getElementById('x');
if (tbl.rows.length == 0) {
   // empty
}