0

My previous post was removed before I could add additional information but lets try this again...

Ive seen other posts similar to this but my adjustments have not been successful.

var table = document.getElementById("report-table");
var rows = table.getElementsByTagName("tr");
console.log(rows.length);
console.log(rows);

0

HTMLCollection []
length: 1077

My table is populated using Jquery+AJAX. I thought issue this might be because of script placement but I moved it to after the table is done filling and the result was the same.

EDIT

$.ajax({
    url: 'test.php',
    type: 'post',
    data: {"order":order, "json":json},
    success: function(json){
        var js = Object.values(JSON.parse(json));
        js = JSON.parse(json);
        js.forEach(function(element){   
            var title = element['title'];
            var date = element['date_stamp'];
            $('#report-table').append('<tr class="report-item"><td>&emsp;'+title+'</td><td>'+date+'</td></tr>');
        });             
    }
});
var table = document.getElementById("report-table");
var rows = table.getElementsByTagName("tr");
console.log(rows.length);
console.log(rows);

HTML

<table class="report-table">
    <tr class="report-head">
        <th colspan="2">Report</th>
        <th colspan="2" class="right">List By : 
            <select id="sort-select" onchange="sort(json)">
            ...
            </select>
        </th>
    </tr>
</table>
<div class="my-table-responsive">
    <table id="report-table" class="report-table">
    </table>
</div>  
FamousAv8er
  • 2,345
  • 2
  • 9
  • 27
  • First change your table `class` to `id`, since the javascript you provided uses `getElementById()` – Cray Mar 05 '20 at 16:35
  • There is a class and an id with the same name. Two tables with the class name and the second table has the id @Cray – FamousAv8er Mar 05 '20 at 16:37
  • 2
    Because your AJAX call is **asynchronous**, the code you moved below that still executes **before the table is populated**. You need to do the stuff in your success handler after `js.forEach`, or start using `async`/`await`. – connexo Mar 05 '20 at 16:50
  • @connexo Thank you for the response. So even though the HTMLCollection shows a length of 1077 `rows.length` would still be zero because its async? – FamousAv8er Mar 05 '20 at 16:52
  • 1
    Because HTMLCollections are *live*, the console tricks you here. At the time of execution,the length is 0. The console does never show you that zero, though. If you do `const a = rows.length;` and then `console.log(a);`you will see `0`. I recommend you stop using `getElementsByWhatever` methods until you are very clear on the subtle differences between the `NodeList` returned by `table.querySelectorAll('tr')`, and an `HTMLCollection` returned by `table.getElementsByTagName("tr");`. – connexo Mar 05 '20 at 16:54

0 Answers0