I was looking to count for table tr elements but in my case I was needed count should be updated in real time. Here is my solution to get tr count real time.
Jquery:
$(document).ready(function() {
// Get initial number of rows
var rowCount = $('#myTable tr').length;
$('#rowCount').text(`Total rows: ${rowCount}`);
// Handle rows being added
$('#myTable').on('DOMNodeInserted', function() {
rowCount = $('#myTable tr').length;
$('#rowCount').text(`Total rows: ${rowCount}`);
});
// Handle rows being removed
$('#myTable').on('DOMNodeRemoved', function() {
rowCount = $('#myTable tr').length;
$('#rowCount').text(`Total rows: ${rowCount}`);
});
});
This code listens for the DOMNodeInserted
and DOMNodeRemoved
events on the #myTable
element. When those events fire (i.e. when rows are added or removed), the code updates the rowCount
variable and displays the updated count in the #rowCount
element.