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

The jQuery function throws an Error that is not caught by the surrounding try / catch block

Recently, I've been enhancing error handling in my JavaScript objects that heavily utilize jQuery. However, I've run into an issue where throwing a new Error from within a jQuery method is not caught by the surrounding catch statement. Instead, i ...

Angular.js enables the ability to display views from several partials that are loaded dynamically

My goal is to create a view composed of multiple partials that are loaded dynamically based on the content type. While I am new to angular.js, my current approach in the controller involves: $(elem).html(string_with_src); $compile(elem.contents())($scope) ...

Using Jquery to retrieve the window size and dynamically apply it to a div's CSS, adjusting it accordingly when the

Hey there! I'm trying to create a full-screen div, but unfortunately CSS doesn't seem to do the trick in this case. JavaScript/jQuery is my only option. My plan is to dynamically set the size of the div based on the browser window's dimensi ...

How can I use CSS to make a child element in a grid layout stretch horizontally to full width?

I am currently working on designing a grid layout that will display a child element when clicked. Here is what I have in mind: [ link1 ] [ link2 ] [ link3 ] [ link4 ] [ link4 ] [ link4 ] When clicked, it will turn into: [ link1 ] [ link2 ] ...

Exploring the Power of jQuery Ajax Requests

Currently, I am making an Ajax call from site.com/users/{username} I need to access the url site.com/account/deleteComment, but when I check in fireBug it seems to be trying to access site.com/users/account/deleteComment Below is the code snippet: $ ...

What is the best way to choose all text within a code box without highlighting the entire webpage?

I developed a CSS code specifically for my blogspot site to organize and store all of my code and technical snippets. .code { background:#dae6ef; background-repeat:no-repeat; border: solid #5C7B90; border-width: 1px 1px 1px 20px; color ...

Refreshing the page following a jquery ajax request results in script malfunction in Firefox

I'm currently in the process of developing a system that updates the language on a website after a user clicks on an item. The functionality works smoothly on Chrome and Internet Explorer, both on desktop (Windows 8.1) and mobile devices. However, whe ...

Create a unique margin using CSS only that will appear at the bottom of a flex-row container that scrolls

I'm trying to create a horizontal scroller with margins between each item and consistent margins at both ends. However, I'm noticing that the margin at the end of the container seems to be disappearing somehow. Is there a way to maintain the mar ...

What is preventing SVG textPath from displaying properly? [Empty output in devtools]

I found this interesting code snippet on Mozilla and decided to incorporate it into a Vue component. <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path id="MyPath" fill="none" stroke="red" d="M10,90 Q90,90 90,45 Q90,10 ...

Creating a multi-level mobile navigation menu in WordPress can greatly enhance user experience and make

Hey there, I am currently in the process of developing a custom WordPress theme and working on creating a mobile navigation system. Although I have managed to come up with a solution that I am quite pleased with after multiple attempts, I have encountered ...

Transferring identifier from ashx page to aspx label or hidden field

I am working on an autocomplete textbox that retrieves data from a database and displays results as the user types. using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select (Patient_First_Name+' '+Patient_Last_Name+' '+ ...

What steps can I take to incorporate a dropdown feature into my existing menu design?

I am currently working on a navigation menu that includes various subjects. One of the subjects is titled Equipment, and when I hover over it, Throwables and Gear appear. However, I now want to add another dropdown menu that opens when I hover over Throwab ...

A dynamic 3-column layout featuring a fluid design, with the middle div expanding based on the

Sorry for the vague title, I'm struggling to explain my issue clearly, so let me elaborate. I am using flexbox to create a 3-column layout and want the middle column to expand when either or both of the side panels are collapsed. Here is a screenshot ...

HTML and CSS: Centering elements inside div containers

Is it possible to align elements within a </div> using the align attribute? For example, as shown in the image below: e1:align="top" e2:align="right" e3:align="bottom" e4:align="left" EDIT: This query is purely for self-learning purposes in HTML ...

The colors of a jVector Map change based on the display of two datasets

I have two sets of data, 'ctrl.gdpData' and 'ctrl.pdpData', which I am currently displaying on the jVector world map as shown below: $('#world-map-gdp').vectorMap({ map: 'world_mill', series: { ...

At times, the AngularJS directive may not be invoked

Here is my custom directive: ppm.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log(& ...

jQuery .load() pause, content loading

Can anyone provide assistance with achieving the desired effect of fading out the #portfolio-wrapper, then loading the portfolio2.html and fading it in? Currently, the load function is executing before the fadeOut operation. Any help would be greatly app ...

I'm curious if there is a method to validate HTML elements within AngularJS. You can check out my app on Plunker [here](https://jsfiddle.net/4jttdczt/)

I'm a newcomer to angularjs and I am attempting to test HTML elements, but my tests are failing. Specifically, I would like to test the value or text contained within an HTML element. Can anyone provide guidance on how I can achieve this? Below is my ...

What makes AJAX take so much time to load?

Hey everyone, I’ve been working on compiling and sending some forms to a PHP file but I've been noticing that the process is quite slow. Even when I use var_dump in PHP to only display the POST values, it still takes a considerable amount of time co ...

Div failing to expand to fit its contents

I'm having trouble getting my info-container div to adjust its height based on its contents. I suspect that the floating div within it might be causing the issue, but I'm not certain. I've included a link to jsfiddle where you can view the C ...