What is the best way to apply different styles to alternative children within a dynamically generated list?

I am currently implementing the following code snippet:

$('.js-toprow:nth-child(even)').css("background:", "#ddd");
$('.js-toprow:nth-child(odd)').css("background:", "#ff0000");

Within the function:

function resetSlides() {
    container.css({
        'top': -1 * item_height
    });

// >> Using it here <<   
}

In order to alternate between two different colors for an element tree.

The complete code can be viewed here (already resolved): "Working" script returning Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The new child element contains the parent

In this scenario, the variable that needs to be styled is "slides", so I experimented with using

slides.css({'background': '#000'});
within the function for testing purposes, and it was successful. However, I still require the even and odd styling.

It is essential to achieve this using jQuery alone since applying CSS leads to restyling of the children as new elements are inserted at the beginning of the list.

Answer №1

To determine whether an index is even or odd, you can simply iterate through the elements and use the modulo operator:

$('.js-toprow').each(function(index) {
    if (index % 2 === 0) { // Even
      $(this).css('background', '#ddd');
    } else { // Odd
      $(this).css('background', '#ff0000');
    }        
});

The modulo operator calculates the remainder when dividing two numbers, here it is used to check if index is divisible by 2. Even numbers will always return a remainder of 0.

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

Having trouble with CSS basics? Seeing properties change across multiple classes?

My CSS skills are still in the beginner stage and I am currently struggling to troubleshoot an issue with my code. The HTML: <div id="loginForm"> <span class="dottedLink"><a href="resetlogin">Recover login details</a></span ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

Determine if a webpage is out of focus using jQuery

Is it possible for jQuery/JavaScript to detect if a user is engaged in other activities and not currently looking at this page? Precision is not necessary, just an approximate idea is fine. ...

Stopping Accordion Title from Moving Vertically in Material-UI

Just finished creating this accordion which will be used as a menu item. However, I've encountered an issue where clicking on the Main title causes the accordion summary to move downward vertically. Any suggestions on how to keep the Main tile fixed ...

Select the five previous siblings in reverse order using jQuery's slice method

I have a unique approach to displaying a series of divs where only 5 are shown at a time using the slice() method. To navigate through the items, I include an ellipsis (...) link after every 4th item, which allows users to easily move on to the next set of ...

Tips for keeping the background image in place while resizing the page

How can I set the background image for the whole page without it changing position with resizing? The image is 3065px in height so that should not be the issue. .bg { background-image: url("#"); height: 3065px; width: 100%; background-positio ...

What is the method for creating a vertical line similar to this one?

I am looking to create a contact information list similar to this: Sample Could someone please advise on how to add a vertical line between the email and hotline sections, as shown in the example image? Thank you in advance! ...

What is the best way to align a GIF and two rows of text within a container div?

Check out my JSFiddle below: In this fiddle, there is an image sized 32 by 32 on the left side and two lines of text on the right. I need help aligning the center of the gif and the text with the middle of the enclosing frame. I've tried adjusting t ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...

The jQuery AJAX function successfully executes, but the MySQL post deletion operation fails to take place

I am encountering an issue with this particular code. The Ajax code runs through to the end and then fades out the parent of the delete button. Below is the code for the delete button, post, and Ajax: <?php include('php/connect.php'); ...

What is the best method to modify the inner HTML of a recently added element?

<script> $(document).ready(function(){ $(this).on("click", "#add", function(){ var html = ' <div id="trav"><div class="adults"><p>Adults</p><div class="buttons&q ...

A mysterious underscore suddenly materializes within Font Awesome icons when used in HTML

Currently, I'm working on the footer section of a webpage using HTML and Bootstrap 5.3.0. I encountered an issue where an underscore appears next to the icons when I add them. I suspect that this is due to the white spaces between the elements, which ...

What could be causing my js.erb file to not function properly?

Here is the code snippet I am working with: file.js.erb alert("Alert"); main.js jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) jQuery.fn.submitWithAjax = function() { this.submit( ...

CSS opacity is currently not working as intended

Why doesn't the opacity work here? I've tried using hex and rgba colors, but nothing changes. Even adding classes to tr and td didn't help... First attempt: .done{ background-color: rgba(0,175,51,5); color:white; opacity: 50; ...

Numerous pop-up windows on a single webpage

I am facing an issue with two modal windows on the same page. When I click on the button with the attribute: data-target='#change', the CHANGE MODAL WINDOW fails to show up. As I lack experience in JavaScript, could the problem be with the follo ...

What is the proper way to add comments within CSS code inline?

Can anyone provide instructions on how to comment an inline css property, such as height, in the following code snippet? <div style="width:100%; height:30%;"> Any help is appreciated. Thank you! ...

What is the best way to center a paragraph vertically around a particular word?

Within this div, I have a paragraph. I am trying to position a specific word within the paragraph to be centered vertically, but my attempts using a span have been unsuccessful. Is there an easy way to achieve this? div { width: 300px; height: 250px ...

Guide to displaying WordPress functions within an accordion in my loop

Currently, I'm working on implementing a vertical accordion feature that will display blog posts within each section. The idea is to have 5 of the most recent posts displayed in the accordion, with each post showing the date (day/month/year) and title ...

Adjusting CSS to switch up the color scheme

Is there a way to allow users to change the background color of pull quotes by using the input type="color tag within a form element? Below is my current HTML structure: <form action="change.php" method="post"> name: <input type="text"> ...

Encountering a blank webpage displaying a warning that reads, "The use of 'event.returnValue' is outdated

Although this issue has been discussed before and was previously considered a bug, I am currently using jQuery v1.11.0, which should have resolved it. The problem I am encountering is that when my page loads, there is supposed to be a slide-in effect (as a ...