简体   繁体   中英

How do you use javascript to count number of rows in a "flat" table

Say I have the following table. How would I show the number of rows in the table using simple javascript within a paragraph <p id="rowscount"></p> .

I am new to javascript so it would be helpful if you can include any comments regarding how to call a function for example.

 <p id="rowscount"></p> <table> <tr> <td>One</td> <td>Two</td> </tr> <tr> <td>One</td> <td>Two</td> </tr> </table>

Suppose you have the table as following:

<div id="rowsNumber"></div>
<table id="myTable">

  <tr>
    <td>One</td>
    <td>Two</td>
  </tr>
  <tr>
    <td>One</td>
    <td>Two</td>
  </tr>

</table>

In some browser the table data rows goes wrapped inside a tbody tag as following:

<div id="rowsNumber"></div>
<table id="myTable">
    <tbody>
      <tr>
        <td>One</td>
        <td>Two</td>
      </tr>
      <tr>
        <td>One</td>
        <td>Two</td>
      </tr>
    <tbody>
    </table>

so define a function like this:

var getTableRowCount = function(tableNode){
  var tbody = tableNode.getElementsByTagName('tbody')[0];
  if(tbody){
   return tbody.getElementsByTagName('tr').length;
  }else{
   return tableNode.getElementsByTagName('tr').length;
  }

}

And call the function passing the table node as parameter for example:

var count = getTableRowCount(document.getElementById('myTable'));
document.getElementById('rowsNumber').innerHTML = 'Total rows = ' + count;

Now if you want to observe a listener so that whenever any tr of the table changes its visibility you need to have a MutationObserver observing on the tr rows. To add mutation observer you can write some code like this:

var observer = new MutationObserver(function(mutations) {
     var count = getTableRowCount(document.getElementById('myTable'));
     document.getElementById('rowsNumber').innerHTML = 'Total rows = '   + count;
  });

//find the target on which to observe
var target = document.querySelector('table tr');

observer.observe(target, {
    attributes: true
});

please try bellow code

 var table = document.getElementById('myTable'); document.getElementById("rowscount").innerHTML = table.childNodes.length;
 <p id="rowscount"></p> <table id="myTable"> <tr> <td>One</td> <td>Two</td> </tr> <tr> <td>One</td> <td>Two</td> </tr> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM