5

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.

benvc
  • 14,448
  • 4
  • 33
  • 54
Phạm Trí
  • 61
  • 1
  • 1
  • 4

6 Answers6

6

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
}
DDan
  • 8,068
  • 5
  • 33
  • 52
1

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

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

More info here

MyTwoCents
  • 7,284
  • 3
  • 24
  • 52
1

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

0

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

if (tbl.childElementCount==0)
{

}

For more details you can refere link

Jitendra G2
  • 1,196
  • 7
  • 14
0

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>
benvc
  • 14,448
  • 4
  • 33
  • 54
-1

Plain javascript:

!![].length 

or use Lodash

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