Exploring discrepancies between two tables with the power of Javascript

const firstTable = document.getElementById('table_1')
const secondTable = document.getElementById('table_2')

const rows1 = firstTable.rows
const rows2 = secondTable.rows

for (let i = 0; i < rows1.length; i++) {
  for (let x in rows1[i].cells) {
    let col = rows1[i].cells[x]
    console.log(col)

  }
  for (let j = 0; j < rows2.length; j++) {


  }
}
table {
  border: 1px solid black;
}

td {
  border: 1px solid black;
}
<table id="table_1">
  <tr>
    <th>id</th>
    <th>name</th>
    <th>age</th>
  </tr>
  <tr>
    <td>1</td>
    <td>per</td>
    <td style="background-color:red">27</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Tom</td>
    <td>25</td>
  </tr>
  <tr>
    <td>notexist</td>
    <td></td>
    <td></td>
  </tr>
</table>

<table id="table_2">
  <tr>
    <th>id</th>
    <th>name</th>
    <th>age</th>
  </tr>
  <tr>
    <td>1</td>
    <td>per</td>
    <td style="background-color:green">25</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Tom</td>
    <td>25</td>
  </tr>
  <tr>
    <td>3</td>
    <td>alex</td>
    <td>33</td>
  </tr>
</table>

I aim to dynamically compare the content of these two tables using JavaScript to visualize the differences between them. Every cell in every row will be compared based on their IDs. If an ID does not exist in the second table, it will be marked as 'not exist'. Additionally, if the cells have different values (e.g. ages), the background color will be styled as either red or green to indicate the difference.

Answer â„–1

When comparing two tables from the DOM to see if they are identical in structure, you can iterate through the TD elements of one table and compare the textContent to the corresponding element in the other table:

Here is an example:

const firstTable = document.querySelectorAll("#table1 td");
const secondTable = document.querySelectorAll("#table2 td");

// Loop through one of the tables if they are identical in structure
for (let i = 0; i < firstTable.length; i++) {
  if (firstTable[i].textContent !== secondTable[i].textContent) {
    firstTable[i].classList.add('redbg');// Add a class if content is not equal
  }
}
.redbg {
  background: red;
}
<table id="table1">
  <tr>
    <th>id</th>
    <th>name</th>
    <th>age</th>
  </tr>
  <tr>
    <td>1</td>
    <td>per</td>
    <td>27</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Tom</td>
    <td>25</td>
  </tr>
</table>

<table id="table2">
  <tr>
    <th>id</th>
    <th>name</th>
    <th>age</th>
  </tr>
  <tr>
    <td>1</td>
    <td>per</td>
    <td>25</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Tom</td>
    <td>25</td>
  </tr>
  <tr>
    <td>3</td>
    <td>alex</td>
    <td>33</td>
  </tr>
</table>

To apply the same concept to your array, iterate through the first array and compare its elements with the corresponding elements in the second array, adding a class if they are not equal while building the table.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover Xml information or Json object displayed as XML tree in Html using Javascript

Looking for a way to display my JSON object or XML data in HTML similar to how React does it. I found this component on GitHub: https://github.com/marushkevych/xml-display-component, but I prefer not to mix JavaScript and React.js. Can anyone offer some gu ...

Sending NodeJS Buffer as form data to Spring Boot in a correct way

I'm facing an issue with my NodeJS application where I am working with an image buffer called qrCode const qrCodeData = Buffer.from(body).toString('base64'); //body received, not sure if base64 is correct f ...

Creating separate UI-views using ui-router within a single module

Can two independent ui-views be created using ui-router for a single module? The objective is to have the ui-views "know" where to display the current state, essentially creating a form of redirection. https://i.sstatic.net/OTNNL.png ...

Issues with Gulp Autoprefixer Functionality

I'm struggling to make Autoprefixer work with Gulp. Despite using opacity, gradients, and transforms in my CSS, I can't see any vendor prefixes being added. However, everything else seems to be functioning correctly. Below is my gulp file: var ...

Function with jQuery click event and namespace

Why is it illegal in jQuery? $('#someElm').on('click', customNamespace.namespaceFunction); jQuery throws an error: Uncaught TypeError: undefined is not a function Note: The functions are not important... let's use them for illus ...

positioning two text sections on the left side of an image

I am attempting to create a page layout with text that should look like this: Team Name My Team Name +-------------+ Division Team Division| | Current Ranki ...

Unlocking the potential of Vue within shadow dom environments

I am facing an issue with a shadow DOM that includes the root element and a Vue component. <template> <div class="container"> <div id="app"></div> </div> <script src="http://my-site.com/app/js/vue-compo ...

What is the best way to send a prop from a parent component to its child using context in React?

Currently, I am working on fetching data in a React application. My goal is to extract an individual value from the response and pass it as a prop in a context from a parent component. The `trendingData` variable holds information retrieved from an API cal ...

Verify whether the input from ng-model is numeric

When utilizing ng-model binding in an input field, data is usually stored as a string. Is there a way to verify if the user has entered a number? ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

The function is missing from the object, leading to a script error with jQuery

When using different versions of jQuery, I encountered some issues with saving changes in my application. Initially, with jquery-1.4.4.min.js, everything worked except for the save function due to an error I made. However, when switching to jquery-1.7.1.mi ...

Is there a way to retrieve the HTML raw code using backticks for string interpolation in JavaScript?

I am working on a resume builder project where the HTML template file is stored in Firebase storage and retrieved using a URL. The template has been modified to include string interpolation, such as <h1>${name}</h1>. However, when I fetch the d ...

rearranging nodes from multiple arrays into a single array and then repositioning them within the parent array using angularjs

[![enter image description here][1]][1]I am working with AngularJS and I have multiple arrays named list1, list2, and list3. Each array is used in a different list. Within my application, there are two buttons and two divs - the left div displays elements ...

Creating packing features specifically designed for resolution within a reusable module

I've decided to revamp my Angular application based on John Papa's style guide (well, mostly) and my main focus is on improving modularity. The stumbling block I've encountered is with route resolves. So far, I've been using a global ap ...

Fetch JSON information from various servers/domains through ajax requests

I am attempting to retrieve JSON data from a different server/domain. My expectation is that the code below should trigger a success alert, but instead, I am getting an error alert $.ajax({ url: "http://xxxx.com/zzzz", ...

There was an issue parsing the JSON data due to a syntax error that was encountered

I came across this code snippet: function pushJsonData(productName) { $.ajax({ url: "/knockout/SaveProduct", type: "POST", contentType: "application/json", dataType: "json", ...

What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure: var newItem = { 'address': "Кабанбай батыр, 53", 'cityId': 1, 'courierName': "МаР...

What could be causing the bootstrap 4 col-md-3 block to shrink when using position fixed?

When working with Bootstrap 4, I encountered an issue where changing the block position from relative to fixed using a script caused the block to decrease in size. The script I used includes a .sticky class: .sticky { position: fixed !important; top: ...

Retrieving information from a hyperlink or input field within a list using jQuery

I'm working with the following script : <script> $().ready(function(){ $('.request_list').click(function(){ requesting_dept = $('#requesting_department_name').val(); alert(requesting_dept); $. ...

Issues with the presentation of HTML DIV elements

I am puzzled by a situation where my HTML layout to present financial data does not seem to update properly in certain browsers. Despite using jQuery and inspecting it with Firebug, the visual display of the parent divs remains unaltered. This issue become ...