Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a table is empty or not using javascript

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.

like image 940
Phạm Trí Avatar asked Oct 30 '18 05:10

Phạm Trí


People also ask

How do you check if a table is empty in HTML?

You know a table is empty if it only contains one row (as a row is dynamically added around your table headers). So you can try and select all the rows within your table and check the length of the collection returned. If the length is less than or equal to 1 then you know that the table is empty.

How do I check if an HTML element is empty using Javascript?

Use the childNodes property to check if a div element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments. If the property returns a value of 0 , then the div is empty.


2 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
}
like image 177
DDan Avatar answered Sep 23 '22 10:09

DDan


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

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

More info here

like image 42
MyTwoCents Avatar answered Sep 23 '22 10:09

MyTwoCents