tr { text-align: center; padding: 5px; } td { text-align: center; padding: 5px; width: 45px; height: 20px; } 
 <table id="tab1" border="1"> <tr> <td>0</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> </tr> </table> <table id="tab2" border="1"> <tr> <th>0</th> <th>2</th> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>4</td> </tr> </table> </body> 
How to compare the contents of two tables using jquery. If they are not the same, then display the message

  • Is this a learning task? Is the number of rows / columns exactly the same, and you only need to compare the values ​​in the cells? - Sergiks

1 answer 1

If it is known that the number of rows and columns is the same, you can simply select all cells ( <td> and <th> elements) in each of the tables through jQuery, and run, comparing the values ​​before the first mismatch

 var t1 = $('#tab1') ,cells1 = $('td,th', t1) ,t2 = $('#tab2') ,cells2 = $('td,th', t2) ,i ; for( i=0; i<cells1.length; i++) { var v1 = cells1[i].innerHTML ,v2 = cells2[i].innerHTML ; if( v1 == v2) continue; // сюда попадаем только когда не равны значения alert("о, ужас! "+v1+" не равно "+v2); break; } 
 table, td, th { border-collapse: collapse;border:1px solid #CCC; margin-bottom:10px} td {text-align: center;width: 45px;height: 20px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table id="tab1" border="1"> <tr> <td>0</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> </tr> </table> <table id="tab2" border="1"> <tr> <th>0</th> <th>2</th> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>4</td> </tr> </table> </body>