Apply a custom CSS class to every `tr` element that includes a particular value

I'm attempting to assign a class to a tr element (last_value_row) in a form when the target value in the first td of the last_value_row element is "New Target". Currently, only the first element will have the class added, while all other elements with the target value "New Target" do not.

This is the HTML portion:

<table id="epoch_forms_table" class="epoch_forms_table">
   <tr class="title_row">
      <th>{% autoescape off %}{% trans "Target name" %}{% endautoescape %}</th>
      ...
      <th class="last"></th>
   </tr>
   <tr class="value_row{% if epoch_form.errors %} error{% endif %}">
      <td></td>
      <td><label><input type="number" size="13" step="0.001"></label></td>
      <td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td>
      <td><a href="#" class="button icon remove remove_row_button danger"></a></td>
   </tr>
   <tr id="last_value_row" class="last_value_row target_background_color">
      <td></td>
      <td></td>
      <td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td>
      <td></td>
   </tr>
   <tr class="error_row">
      {% for field in epoch_form %}
         <td>{{ field.errors }}</td>
      {% endfor %}
      <td></td>
   </tr>
</table>

Here is the JavaScript code I am using:

var new_target_element = document.getElementById("last_value_row");
var last_values = [];
var index = $("#epoch_forms_table tr.value_row").index(value_row);


...
for (let i = 0; i < el.length; i++) {
   for (let i = 0, cell; cell = new_target_element.cells[i]; i++) {
      if ($(this).find("td:contains('New target')")) {
         new_target_element.classList.add("new_target_color");
         new_target_element.classList.remove("target_background_color");
      } else {
         new_target_element.classList.add("target_background_color");
         new_target_element.classList.remove("new_target_color");
      }
   }
}
 if (last_values[index].length === 0) {
            last_value_row.find("td:first").html("New target");
        } else {
...
}
}

I am striving to toggle the CSS class "new_target_color" on every "last_value_row" depending on whether or not there is a target value "New Target" in the first td. However, currently, only the first element consistently changes its class.

Answer №1

It seems that focusing on the row with an ID labeled as last_value_row may be misleading. Instead, the goal should be to locate rows with a specific class attribute (otherwise, the search might lead to identifying unique values or delving into nth child complexities).

// Locate all rows with the class 'last_value_row'
var lastValueRows = document.querySelectorAll('.last_value_row');

// Function for modifying classes based on content
function updateRowClasses(row) {
    // Check if the first cell contains 'New Target'
    var isFirstCellNewTarget = row.cells[0].textContent.trim() === 'New Target';

    // Update classes according to condition
    if (isFirstCellNewTarget) {
        row.classList.add("new_target_color");
        row.classList.remove("target_background_color");
    } else {
        row.classList.remove("new_target_color");
        row.classList.add("target_background_color");
    }
}

// Iterate through each 'last_value_row' and execute the function
lastValueRows.forEach(updateRowClasses);

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

AngularJS View not updating when navigating to a third level nested route using angular-ui-router

I'm currently working on organizing my routes with three levels using ui-router. I'll just provide a snippet of my routes that is causing an issue, as they are quite extensive and including everything here may be overwhelming. If you feel more d ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

Utilizing regular expressions with the re_path function in Django 2.0

As a beginner in Python and Django, I apologize if this question seems too easy. I've attempted to implement this in CreateView without success: re_path(r'^<str:pk>/$', indexView.as_view(), name='index'), Could someone ple ...

Struggling to iterate through a massive JavaScript object using a for loop

Presented is a sizable javascript object: {"raw": null, "entities": ["CLOUD14", "ABUSE2916-ARIN", "ADMIN2521-ARIN", "NOC11962-ARIN"], "asn_registry": "arin", "network": {"status": null, "handle": "NET-104-16-0-0-1", "name": "CLOUDFLARENET", "links": ["htt ...

Exploring the benefits of utilizing useState and localStorage in Next.js with server-side

Encountering an error consistently in the code snippet below: "localstorage is not defined" It seems like this issue arises because next.js attempts to render the page on the server. I made an attempt to place the const [advancedMode, setAdvanced ...

What could be causing the variable to be undefined in the template?

I encountered an error message 121| <div class="container-fluid bg-dark text-white" style="margin-top: 2%;"> 122| >> 123| <h1 class="mb-1 text-center"><%= article.title %> < ...

What is the best way to overlay a video onto an image using HTML and CSS?

Currently, I am experimenting with a layering technique in HTML/CSS. The idea is to place an image behind a video to enhance the overall look of the video section. Here is a sample photoshop mockup that demonstrates what I am aiming for: HTML div id= " ...

Is there a way to shift the button over to the left?

I am currently utilizing the modalExample provided in the Bootstrap documentation. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Open modal</button> <di ...

Pass the chosen option to PHP using Ajax within the same webpage, utilizing HTML

My Goal: I am working on a HTML/PHP page that displays the home page of my website. One section on this page is dedicated to highscores, with data retrieved from a database. Users can use a Select box to choose how the highscores are sorted. View the high ...

Twitter Bootstrap - Uniform column spacing and consistent heights

Working on a layout design using Twitter Bootstrap 3. Here's the current progress: <div class="container"> <div class="row"> <div class="col-xs-3 red"> <h3>Column 1 Content</h3> <im ...

Guide on positioning the camera to track the model in a third-person view

Currently, I am tackling a project in Three.js where I am in need of setting up a third-person camera that tracks a 3D model as it navigates through the scene. Despite having a basic framework with animations and controls, I am encountering difficulties in ...

Having trouble with if else conditions in a Django template?

I'm currently developing a system for sending friend requests as part of my project. Below is the implementation I have set up where one user can send a request to another. If users are not friends (the relationship does not exist in the friends o ...

Retrieve the index of the item that has been selected in a dropdown list

<select ng-click="getIndex($index)" size="14" ng-model="playlist.fileSelected" ng-options="saveFile for saveFile in playlist.playlist"></select> When I try to access $index, it shows up as undefined. Is there a way to retrieve the index of the ...

Issue detected: The PNG file being used with jspdf is either incomplete or corrupt

I am trying to insert two images into my pdf when the "create-pdf" icon is clicked. The first image is a canvas that converts to an image successfully. var canvas = document.getElementsByClassName("jade-schematic-diagram"); img = canvas[0].toDataURL("imag ...

Issue with Jquery code on Mac OS Chrome - it's functional on Windows 10 Chrome though!

Upon clicking the image, it should hide and the YouTube video plays automatically. This functionality works perfectly on Windows 10 but is not functioning on Mac OS or iOS. I am seeking assistance in resolving this issue. I do not own a MacBook, but my c ...

JavaScript Function to Convert JSON Data into an Excel File Download

I am looking for help with converting JSON data received from an AJAX POST Request into an Excel file (not CSV) for download on a button click. The JSON Data may contain blank values and missing fields for each JSON row. I have attempted to achieve this o ...

What is the best way to assign a Python variable to an <a-assets> element?

There exists a Python function that provides the chosen background <a-sky ID="sky" color="{{object.background}}"></a-sky> The backgrounds can be in the format of '#c6aa99', '#e1a600', '#290942', 'star' ...

Has anybody successfully implemented the danfojs-node package on an Apple M1 chip?

I encountered an issue when trying to use danfojs-node on a Mac with an M1 chip - it kept crashing due to TensorFlow. I'm curious if anyone has managed to successfully integrate the npm package from this link (https://www.npmjs.com/package/danfojs-nod ...

Validate Email and Phone Number using Javascript

How can I create a Javascript function to validate an HTML form? Currently, my form validation only checks if a field is empty. I want to enhance it to also validate the email format and ensure the phone number is numeric. Currently, the form displays a po ...