How can I reset the alternating table row in a new table using CSS?

I am encountering an issue with alternating row colors in my tables. Even though I have two separate tables, the tr:odd rule is being applied across both tables.

Below is the HTML for my tables:

<table class='myTable'>
    <tr class='myRow'>
        <td>row 1</td>
    </tr>
    <tr class='myRow'>
        <td>row 2</td>
    </tr>
    <tr class='myRow'>
        <td>row 3</td>
    </tr>
</table>
<hr>
<table class='myTable'>
    <tr class='myRow'>
        <td>row 1</td>
    </tr>
    <tr class='myRow'>
        <td>row 2</td>
    </tr>
</table>

Here is the CSS:

.myAltRowClass { background: #DDDDDC; }

And the JavaScript:

$(".myTable .myRow:odd").addClass('myAltRowClass');

You can view the jsfiddle: http://jsfiddle.net/niner/Sgq9T/

My problem is that the first row of the second table is starting with the alternate color, when it should start with the normal (white) color. Any assistance on this would be greatly appreciated. Thank you.

Answer №1

Yes, you can achieve this by selecting the rows of each table independently:

$(".myTable").find('.myRow:odd').addClass('myAltRowClass');

Check out the JS Fiddle demo.

Alternatively, you can simply apply CSS to accomplish the same effect:

table.myTable tr:nth-child(even) {
    background: #DDDDDC;
}

View the CSS-only JS Fiddle demo.

Keep in mind that the CSS :nth-child() selector uses `even` because CSS counts from one, unlike JavaScript which starts at zero.

You can also combine both methods by doing:

$('.myTable tr:nth-child(even)').addClass('myAltRowClass');

See the combined approach in action on JS Fiddle.

Answer №2

To achieve alternating row colors in a table using jQuery, you can utilize the CSS3 selector :nth-child(odd) or even depending on your specific requirements. It is recommended to use :nth-child(odd) as it is natively supported and allows jQuery to utilize the more performant native querySelectorAll method. On the other hand, :odd is not a natively supported selector, as mentioned in the jQuery documentation.

$(".myTable .myRow:nth-child(odd)")
    .addClass('myAltRowClass');

For a demonstration, you can check out the jsFiddle Demo.

Answer №3

It's worth mentioning that jQuery's pseudo-class selectors like :odd, :even, and others may not work exactly as you anticipate. These selectors actually target elements based on their position within the jQuery array generated by the preceding selector. For example, when you use $('.myTable .myRow:odd'), it's like creating a temporary array of elements from $('.myTable .myRow') and then excluding the elements with even indexes. The same principle applies to :even, :first, and similar selectors (although nth-child() operates differently and aligns more with expectations).

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

"Include a song in a playlist without the need to sign in - Spotify API

I am looking to create a playlist where users on my website can collaborate, even if they are not logged into Spotify. I want these users to have the ability to add songs to the playlist. Below is the Ajax code snippet that I have: $.ajax({ dataType: &a ...

Ways to integrate mouse out functionalities using an if condition

I'm currently working on a menu using Javascript where clicking on one option will dim the other options and reveal a sub-menu. I'm looking to include an if statement in the function so that when a user mouses out of both the sub-menu and the cli ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Developing Angular 6 for dynamic HTML navigation tabs

Being new to Angular 6, I recently created tabs in HTML and now need to convert them into Angular 6 while also making them dynamic. Here is the original HTML code: <ul class="nav nav-tabs side_nav" role="tablist"> <li role="presentation" class= ...

implement an angular directive to apply a CSS element

I am utilizing AngularJS and ng-repeat to populate a dynamic list of studies. This list has the capability to toggle into child elements of each item, creating an accordion-style toggle list that can go up to three levels deep for each list item. I am curr ...

Include a class in the <code> element if it is not nested within a <pre> tag

I am incorporating the Highlight.js script on my website built with DocPad. I am looking to enhance the appearance of a basic <code> tag (equivalent to `` in Markdown), but this conflicts with the existing styles applied by Highlight.js. Highlight. ...

Trouble with applying position absolute to pseudo element in Firefox version 12 and higher

I seem to be running into an issue with the positioning of a pseudo element in Firefox version 12 or higher (possibly even earlier versions). Despite having position:relative on the anchor tag, the element appears to be relative to the entire page. Any ide ...

Issue with CSS on various mobile devices

Using this CSS to display a fixed part at the bottom of the mobile screen, I noticed that it works well on the Samsung Grand Prime but appears narrower on the Samsung J7 Max. Here is the code snippet and images for reference: .footer { position: fixed ...

-moz-box-reflect - Styling for FireFox

I've been attempting to achieve a similar effect to this tutorial at http://designshack.net/tutorialexamples/HoverEffects/Ex5.html. However, I'm encountering issues with getting the reflection of the image to display properly in IE and Firefox. H ...

How can I implement a pause in my JavaScript code?

Below is a snippet of code that I am using in my project: $.ajax({ url: $form.attr('action'), dataType: 'json', type: 'POST', data: $form.serializeArray(), success: function (json, textStatus, XMLHttpRequest) { ...

Duplicating a Bootstrap theme in Orchard CMS

Currently, I am working on creating my own theme by utilizing the Bootstrap theme from Orchard dashboard as the foundation. However, when I try to launch the site using my theme (without any modifications, simply a clone of Bootstrap), an error appears: "o ...

Concealing and Revealing a Div Element in HTML

Every time the page is refreshed, I am encountering a strange issue where I need to double click a button in order to hide a block. Below is the code snippet for reference: <!DOCTYPE html> <html> <head> <meta name="viewport&quo ...

Is it possible to display a complete list of my items along with their parameters using jQuery ajax?

My function code is set up to display all the items from my list of discipline codes, but I'm facing issues viewing them due to data:{params} always being present. alert('Could not retrieve data'); Any assistance would be greatly appreci ...

Unexpected glitch in my jQuery code is causing an event to fail triggering

I am trying to make an ajax request using the code below: jQuery.ajax({ type: 'GET', url: '/logical_interface/delete', context: this, // I had to add this line to make the success function work, even though I don't ful ...

The jQuery find and replace feature is causing my entire content to be replaced instead of just specific paragraphs

Within this section, there are multiple paragraphs and an input field. The concept is simple: the user inputs text into the box, then hits "ENTER" to trigger a jquery function below. The process involves identifying matches between the paragraph content a ...

Harvesting data from an HTML document using BeautifulSoup and Python

I am currently working on extracting text from an HTML file. The HTML file has the following structure: <li class="toclevel-1 tocsection-1"> <a href="#Baden-Württemberg"><span class="tocnumber">1</span> <span class= ...

Setting the size of a box using CSS in HTML pages

I am facing issues with resizing boxes. Below is the code snippet: <!DOCTYPE html> <html lang="en"> <head> <style> .wrapper { text-align: center; } #bubble { display: inline; -moz ...

image in responsive css design

Image 1 (Current Layout) Image 2 (Desired Layout) I am trying to achieve a responsive layout similar to the second image. However, I seem to be stuck with the layout from the first image. Here is the CSS code I'm currently using: @media (max-width ...

The bootstrap modal display issue: black background visible

In my HTML file, there are two modal dialogs that seem to be causing an issue. Interestingly, whichever modal dialog is placed first in the sequence of the HTML code displays properly when the button is clicked (and vice versa). Both modal dialogs have u ...

What is the proper method for integrating the next.js Image component with the HTML <picture> element?

When it comes to optimizing images, Next.js offers an Image component that lazy loads images and includes a srcset for a particular image. However, there are instances where we need to serve different images based on the device being used (art redirection ...