How to check a table is empty or not using javascript

Viewed 15722

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.

6 Answers

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
}

If you want to check if there are any inside table do this

document.getElementById("myTable").rows.length

More info here

you can Check the Row Counts

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

if the tbl.rows.length is 0 that means the table don't have any rows

There are multiple ways. One of way, you can use childElementCount property.

if (tbl.childElementCount==0)
{

}

For more details you can refere link

In this case, since there are no child elements or text nodes in your table, you can just check to see if the innerHTML property is falsy. This prevents your createtable function from appending additional children after the function has been run once. For example:

function createtable() {
  var tbl = document.getElementById('x');
  if (!tbl.innerHTML) {
    var tbdy = document.createElement('tbody');
    tbl.setAttribute('border', '1');
    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>

Plain javascript:

!![].length 

or use Lodash

_.head([]);
// => undefined
Related