jQuery method for implementing alternating row colors that are not sequential

Starting from scratch here. I've fetched a table from a remote server where odd rows are white and even rows are grey. Some rows have been hidden:

$("td").filter(function(){ return $(this).text()=='R1';}).text('Row1'); //white
$("td").filter(function(){ return $(this).text()=='R2';}).text('Row2'); //grey
$('tr:nth-child(3)').hide();                                            //white
$("td").filter(function(){ return $(this).text()=='R4';}).text('Row4'); //grey
$('tr:nth-child(5)').hide();                                            //white
$("td").filter(function(){ return $(this).text()=='R6';}).text('Row6'); //grey
$("td").filter(function(){ return $(this).text()=='R7';}).text('Row7'); //white

The alternating row pattern is now disrupted, making it white, grey, grey, grey, white. How do I revert to the original alternating colors? Applying a class like:

$("tr").filter(":even").addClass("even");
+ css
tr.even td{background-color: blue;}
results in white, blue, blue, blue, white which still doesn't alternate.

I can achieve this with:

$('tr:nth-child(4)').each(function(i){ $(this).find('td').css('background-color', 'white');});
, making it white, grey, WHITE, grey, white. However, there's an issue! Row 4 contains red cells that should remain red. The previous code turns them white instead.

The style provided by the server is:

<script src="remoteserver/sorttable.js"></script>
<style type = "text/css">';
    td.datacellone{
        background-color: #C0C0C0;
    }
    th.datacellheader{
        background-color: #6A5ACD;
    }
    td.alert{
        background-color: #FF0000;
    }
    td.orange{
        background-color: #FFA500;
    }
    td.green{
        background-color: #008000;
    }
</style>

The goal is to maintain the red alert color while restoring the alternating white and grey rows.

Answer №1

If you have CSS classes named even and odd, you can try out this code snippet:

var $rows = $('tr').removeClass('even odd').filter(':visible');
$rows.filter(':even').addClass('even');
$rows.filter(':odd').addClass('odd');

This code removes any existing even and odd classes from the table rows, then applies the classes only to the visible ones using the :visible selector.

Check out this demo (which also demonstrates that individual cells are not impacted by row classes): http://jsfiddle.net/J5DqP/1/

Answer №2

One straightforward method is to reapply the classes.

 var $table = $('table');
 $('tr:even', $table).addClass('even');
 $('tr:odd', $table).addClass('odd');

  //Remove 1 td

  $('tr', $table).removeClass('even odd'); // Remove both the classes
  $('tr:even', $table).addClass('even');
  $('tr:odd', $table).addClass('odd');

**EDIT**

If you wish to modify the styles being applied, substitute

td.alert{ background-color: #FF0000; }

with

tr td.alert{ background-color: #FF0000; }

OR

tr.odd td.alert, tr.eventd.alert, { background-color: #FF0000; }

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

Creating personalized columns in a BootstrapVue table

I'm having an issue with the b-table component in bootstrap-vue. The array containing my items is structured like this: [{ id: 1, name: "Test", phone: 555-111-666, address: "Some Address", //etc... }] I have a couple of question ...

My approach to using this style in React involves utilizing the class attribute as follows: "class[attribute]" [Updated version 2]

When trying to customize an element based on its attribute, the process is a bit different in React compared to pure CSS. Here's an example: <div class='something' data-test='4'></div> ... .something[data-test] { bac ...

I find myself having to double-click the Jquery submit button

Can anyone help with an issue I'm having where I need to click a div button twice for the link to work properly? Thank you <div class="toolbar"> <table width="100%"> <tr> <td class="toolbar-button" title="Print Data" id ...

Toggle between weekends and weekdays on FullCalendar

Is there a way to customize Arshaw's FullCalendar by toggling the display of weekends and changing the timeslot interval dynamically? To elaborate: //Clicking a button to toggle the display of weekends $('#weekend-yes').click(function( ...

How to integrate the Noty plugin with an Ajax function using jQuery

Is it possible to use the noty plugin for displaying messages while making ajax calls? I needed to create two noty notification boxes, one in the beforeSend function and another in the success callback. $('#insert').on('click', functio ...

When the textfield mui is set to shrink, an additional space appears in the label when using a font size of 12px

Struggling to customize the appearance of the textField component, particularly with the label when it is minimized: import * as React from "react"; import TextField from "@mui/material/TextField"; import { createTheme } from "@mui ...

Is there a potential issue with descender tags causing the malfunction of HTML and CSS tags?

Having some trouble with my <p> tag in the CSS. Can't seem to figure out why it's not working correctly. Any help is appreciated. Here's the HTML: <body> <section> <section id="pictures"> <div> < ...

Storing chosen choices from various select lists with similar class name in JavaScript

I am struggling to save all the selected options in an array for future output. Despite trying various suggestions, I haven't been able to make it work yet. The class names and names cannot be modified. HTML <select class="addon addon-select" nam ...

jQuery UI Datepicker Display Issue

I'm encountering an issue with a jQuery UI Datepicker object that is supposed to appear when I click inside a textbox. Below is the HTML code: <tr> <td class="label-td"><label for="dateOpen_add">Date Opened</label></td& ...

Ensure that the floated element stretches to 100% height in order to completely fill the page

I'm working on achieving a height of 100% for the left sidebar so that it fills the page regardless of the size of the "main" div. Currently, it stops at the normal page height and doesn't expand further. Is there any way to make this work as i ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

Move the button to the following line and center it. Ensure that the background image remains at full size

.home{ background-image:url("https://cdn.pixabay.com/photo/2016/12/27/21/03/lone-tree-1934897_960_720.jpg"); background-repeat: no-repeat; height: 100vh; display: flex; align-items: center; justify-content: center; } .hero-text{ fon ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Delaying the return statement

Similar Inquiry: JavaScript asynchronous return value / assignment with jQuery I'm looking for a prototype of a chart with a constructor, and I came up with this implementation: function Chart(file) { var chart = undefined $.getJSON(file, f ...

HTML and CSS are distinct entities with their own individual purposes and

Can you create custom entities? For example: &longline; --> ----------------------------- and then incorporate it in HTML code: <div> &longline; bla bl bla </div> ...

Execute functions in a random order

My array contains a series of functions and is structured as shown below: var all_questions = [ show_question(1, 1), show_question(2, 1), show_question(3, 1), ]; I'm interested in executing those functions within the array in a random or ...

set a hyperlink for the dropdown selection bar

My question is quite simple! I have a database project using PHP, but we are required to use a language that we are not very familiar with. I want to create a drop-down list of different types of cuisine using PostgreSQL (see code below for an example). Th ...

Unnecessary additional spacing caused by inline blocks in Firefox

On my webpage, I have organized my div elements using inline-block properties. Strangely, Firefox is adding extra spacing between two specific divs, while Safari and Chrome display the design consistently. Check out this example here. #main { display ...

Divide the page vertically. On the left side, feature an eye-catching image, while on the right side,

While I have a good understanding of bootstrap 5, I am currently working on a project that requires me to split the page down the center. However, I also need to incorporate a container in the middle that sets a boundary for the text so it doesn't exp ...

Is there a way to dynamically update the content of <li> tag with values from an array every x seconds

I am trying to create a li list using jQuery that will update every 2 seconds with new content, similar to game news updates. However, I'm encountering an issue during the first cycle where it skips the second item in the array. The subsequent cycles ...