Color the text differently if the values are not the same (CSS and jQuery only)

In my code snippet below, you can see a set of HTML elements with specific classes and values:

<div class="verizon-data-duplicate-device-key-89148000004605691537 k-content k-state-active" style="float: left; opacity: 1; display: block;" id="3cf455cc-9777-446b-b733-c60795e419e7-3" role="tabpanel" aria-expanded="true">
    <table style="border-collapse: collapse; padding: 3px; border: 1px solid grey;">
        <tbody>
            <tr>
                <td colspan="2">
                    Verizon Information:
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Account Name
                </td>
                <td>
                    <span>0442047510-00001</span><br>
                    <span>0442047510-00001</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Billing Cycle End Date
                </td>
                <td>
                    <span>2021-07-01T00:00:00</span><br>
                    <span>2022-01-12T00:00:00</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Carrier Name
                </td>
                <td>
                    <span>null</span><br>
                    <span>null</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Service Plan
                </td>
                <td>
                    <span>40515x48526x75802x84777</span><br>
                    <span>M2MPublicDynamic</span><br>
                </td>
            </tr>
        </tbody>
    </table>
</div>

The page contains several similar divs with different class value keys as shown here:

div class="verizon-data-duplicate-device-key-**89148000004605691537** k-content k-state-active"

where 89148000004605691537 is variable.

I am looking to change the text color to red for cases where the values inside span tags within the same td element are different.

For example:

<td>
       <span>2021-07-01T00:00:00</span><br>
       <span>2022-01-12T00:00:00</span><br>
   </td>

should be displayed in red font color

while

<td>
           <span>0442047510-00001</span><br>
           <span>0442047510-00001</span><br>
       </td>

should remain unchanged.

The comparison should only occur within the same td element. Additional CSS classes can be utilized for this purpose.

How can I achieve this implementation?

Answer №1

  $("table td").map(function(e) {
        if($(this).children("span").length){
            if($(this).children("span").contents()[0].textContent != $(this).children("span").contents()[1].textContent){
                $(this).addClass("text-danger"); 
            }
        }
    });
.text-danger {
    color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="verizon-data-duplicate-device-key-89148000004605691537 k-content k-state-active" style="float: left; opacity: 1; display: block;" id="3cf455cc-9777-446b-b733-c60795e419e7-3" role="tabpanel" aria-expanded="true">
    <table style="border-collapse: collapse; padding: 3px; border: 1px solid grey;" border="1">
        <tbody>
            <tr>
                <td colspan="2">
                    Verizon Information:
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Account Name
                </td>
                <td>
                    <span>0442047510-00001</span><br>
                    <span>0442047510-00001</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Billing Cycle End Date
                </td>
                <td>
                    <span>2021-07-01T00:00:00</span><br>
                    <span>2022-01-12T00:00:00</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Carrier Name
                </td>
                <td>
                    <span>null</span><br>
                    <span>null</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Service Plan
                </td>
                <td>
                    <span>40515x48526x75802x84777</span><br>
                    <span>M2MPublicDynamic</span><br>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Answer №2

//looking for cells with two spans
//if the two spans have different text content, apply a red color class to them
$('td').each(function(){       
      const $td = $(this);
      const $spans = $td.find('span');
     
      if($spans.length === 2){
          if($spans[0].textContent !== $spans[1].textContent){
              $spans[0].classList.add('color-red');
              $spans[1].classList.add('color-red');
          }
      }
});
.color-red{
  color:red;
}
<div class="verizon-data-duplicate-device-key-89148000004605691537 k-content k-state-active" style="float: left; opacity: 1; display: block;" id="3cf455cc-9777-446b-b733-c60795e419e7-3" role="tabpanel" aria-expanded="true">
    <table style="border-collapse: collapse; padding: 3px; border: 1px solid grey;">
        <tbody>
            <tr>
                <td colspan="2">
                    Verizon Information:
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Account Name
                </td>
                <td>
                    <span>0442047510-00001</span><br>
                    <span>0442047510-00001</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Billing Cycle End Date
                </td>
                <td>
                    <span>2021-07-01T00:00:00</span><br>
                    <span>2022-01-12T00:00:00</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Carrier Name
                </td>
                <td>
                    <span>null</span><br>
                    <span>null</span><br>
                </td>
            </tr>
            <tr>
                <td style="text-align:right;">
                    Service Plan
                </td>
                <td>
                    <span>40515x48526x75802x84777</span><br>
                    <span>M2MPublicDynamic</span><br>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<script
  src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
  integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
  crossorigin="anonymous"></script>

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

Is JQueries Live functionality compatible with IE8?

Incorporating the JQuery fancy box, I have implemented a pop-up form with select fields that dynamically update a span element upon selection change. Although it works well thanks to fellow Stack Overflow users' help, it unfortunately does not functio ...

Issues with Image Loading in Azure WebMatrix

I am currently using WebMatrix to host my website, but I'm facing some issues with certain elements not loading correctly. Specifically, I have two pictures on my site that are linked to a directory on my local machine. I would like to know how I can ...

Once AJAX has successfully retrieved the data

I am exploring the option of using jQuery ajax to fetch data from a database and display it asynchronously. However, I am faced with the challenge of achieving this without refreshing the entire page each time. For instance, the PHP file called during an ...

Steps to effectively pass parameters in a function object literal

As a JavaScript beginner utilizing an object literal pattern, I am attempting to pass integers as min and max parameters to a function in order to retrieve a random number for use in another function called "interaction". However, I encountered the error m ...

Does setting white-space:nowrap enlarge the div?

My CSS code for div .name sets the width to 75% to truncate text if it doesn't fit. However, resizing the window causes the text to remain the same size and my entire website structure falls apart. This is the HTML code snippet: <tr> <t ...

Success Turns Sour with jQuery Ajax Error

I've been experimenting with Mustache.js and the GitHub API, but I encountered an issue when trying to load more results that don't actually exist. I was hoping to display a message or generate an error in such cases, but my attempts have not bee ...

Using Knockout to bind an element to the selected value from a dropdown list

When using the following select, I am connecting it to an observable array. <select id="selectProtocols" data-bind="options: optionsAvailable, optionsCaption:'Selecione...', optionsText: 'SimpleDescription', optionsValue:'???&a ...

The navigation bar is missing from the screen

Where is the navbar in this snippet? Did I overlook something important? If so, what? <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <div class="container"> <div class="navbar nav ...

Problem with logging in using ajax

I'm attempting to implement an on-page login feature. It functions perfectly without the use of ajax. Below is my login.php code; if($_POST) { $username =$_POST["username"]; $password =$_POST["password"]; $query = $handler->query("SE ...

What is the process for changing the output paper size to A4 in React Native (expo android)?

Using React Native to develop an Android app for billing purposes, I encountered an issue with the output paper size being 216mmX279mm instead of the standard PDF size of 210mmX297mm. Utilizing expo-print and printToFileAsync from expo, I aim to achieve a ...

What is the best way to expand the subcategories within a list?

I have successfully implemented a script to open my hamburger menu. However, I am facing an issue with subitems as some list items contain them. How can I modify the script to ensure that the subitems expand when clicked instead of just hovering? functi ...

What could be causing the shadowbox not to display in Internet Explorer?

I am currently working on fixing a shadowbox issue in Internet Explorer. The page where the shadowbox is located can be found at this link: Here is the HTML code: <div class="hero-image"> <a href="m/abc-gardening-australia-caroli ...

Is there a way to conceal an element on a webpage using jQuery and possibly CSS without causing it to collapse or animate?

Below is the hidden span that needs to be displayed: <span class="lastSave" name="lastSave">Last Saved by <i name="lastSavedBy"></i> at <i name="lastSaved"></i> </span> There is a table located beneath this on the page ...

Error in jQuery AJAX: SyntaxError - unexpected colon character

When using jquery ajax for a cross-domain request, I encountered an error: $.ajax({ type: 'get', url: 'http://someurl', dataType : "jsonp", jsonp: 'callback', success: function (data) { } }) The erro ...

Troubleshooting Guide: Issues with Bootstrap 3 Modal Window Implementation

This question is so simple that it's embarrassing. I attempted to copy the code from http://getbootstrap.com/javascript/#modals directly into a basic page setup, but it's not functioning. It seems like I'm making a very silly mistake. Here i ...

What is the best way to turn my thumbnail into a clickable link while having the title positioned to the right?

Is there a way to create a thumbnail that acts as a link and position the title next to the thumbnail? I have experimented with using 'after' and modifying the HTML structure to align them horizontally. Any ideas on how I can achieve this layou ...

How can I create a tooltip or something similar for an HTML input field?

Seeking a solution for adding additional information to an HTML input field while typing or hovering over it. Attempted the following code snippet: <input type="text" onmouseover="window.status='hello world'; return true;" name="TextInput" ta ...

What is the process to create a sticky Material UI grid element?

Currently, I am in the process of developing the front-end for a shopping cart. To organize the content, I have split the container into two columns using Grid container and Grid item. In each column, various components are placed - the left side containin ...

Choose a specific 24-hour range with the Date Interval Selector

I am currently utilizing the Date Range Picker plugin for bootstrap from the website http://www.daterangepicker.com/#examples, and I have a requirement to set the maximum date time range to be within 24 hours. Below is an example demonstrating how I can s ...

Conceal/reveal div with initial partial visibility

http://jsfiddle.net/7RDBk/1/ At the moment, I am using slideUp and slideDown functions to hide and display a div. My goal is to have 25px of the div showing initially before expanding and going back to 25px when clicked. It seems like a simple task, but I ...