Listening for changes in the number of rows in a table

I used an html table. My requirement: I want to listen for line count changes. Is there anyway to achieve this?

Note. I have no add / remove line functions to achieve.

Moreover, I have tried this,

$("#myTable>tbody>tr").watch("length", function () {
    alert("row count changed..")


But the above code doesn't work for me. Can any of you know how to do this?

Thanks in advance,



source to share

4 answers

The only cross-browser way to do this at the moment would be with setInterval and possibly a custom event.

setInterval(function() {
    var $t = $("#myTable"),
        rowCount = $"rowCount"),
        rowLength = $t.find("tbody").children().length;
    if (rowCount && rowCount !== rowLength) {
        $t.trigger("rowcountchanged").data("rowCount", rowLength);
    else if (!rowCount) {
        $"rowCount", rowLength);

}, 50);​


I suggest firing the event manually when the number of rows changes, rather than using an interval if possible.

Use the jqGrid event refresh


var rowCount = $("#gridid>tbody>tr").length;
   refresh: function(){ 
      var currCount = $("#gridid>tbody>tr").length;
      if (currCount !== rowCount) {
          alert("Number of rows changed!");
          rowCount = currCount;


If you manually delete any lines on click, you will also need to run your code if it does not reload the grid.



You can monitor the DOM DOMSubtreeModified event (note that the event is deprecated, so if anyone has a suggestion for a better event to monitor, please change that) that fires when the DOM tree changes. We can use jQuery's bind function to trigger a function when an event is triggered on the table. This function can check if the number of lines has changed.

var numberOfRows = $("#myTable>tbody>tr").length;
$("#myTable").bind("DOMSubtreeModified", function() {
    if($("#myTable>tbody>tr").length !== numberOfRows){
        numberOfRows = $("#myTable>tbody>tr").length;
        alert("row count changed..");


Try it!

See: Is there a JavaScript / jQuery DOM change listener?


source - you can use this. But there is no implementation or polyfill in IE.

Also you can check TR counter with timer-triggered function.



I did it once with a timer. It's not very pretty, but it works in almost every browser I guess ...

var html;
setInterval(function() {
    var table = $('table');
    if($('table').html() != html){
        html = $('table').html();
}, 500);




All Articles