Different color for background of division

I am working with a structure that looks like this:

<div class="wrapper"...>
   <a href="#"...>blah</a>
   <div class="post"...>stuff</div>
</div>

This structure repeats multiple times on a dynamic page. I am looking for a way to alternate the background colors of the div with class "post" using two different colors. However, CSS's nth-child pseudo class only works with directly sequential items.

Can someone suggest a solution (CSS, Javascript, jQuery, etc.) to achieve alternating div background colors?

Answer №1

Utilizing jQuery's :odd and :even selectors can make styling elements easier:

$(".post:even").css("background-color","blue"); 
$(".post:odd").css("background-color","red"); 

Example HTML structure:

<div class="wrapper">
   <a href="#">content here</a>
   <div class="post">more content here</div>
</div>
<div class="wrapper">
   <a href="#">additional content</a>
   <div class="post">even more content</div>
</div>
...

Visit this link for a live example.

UPDATE:

If you prefer a non-jQuery, JavaScript solution, consider the following approach:

var posts = document.getElementsByClassName("post");
for(var i=0;i<posts.length;i++) {
  posts[i].classList.add(i % 2 === 0 ? "even" : "odd");
  //or
  posts[i].style["background-color"] = i % 2 === 0 ? "blue" : "red";
}

Answer №2

using jQuery:

$('.entry:even').css('background-color','green');
$('.entry:odd').css('background-color','red');

Answer №3

In my usual practice, I implement a system where I assign a CSS class of either "odd" or "even" on the backend. For instance, if the page is being dynamically created in PHP, the code would look something like this:

for ($i = 0; $i < count($rows); $i++) {
  $css_class = 'wrapper ';  
  $css_class .= $i % 2 == 0 ? 'row_odd' : 'row_even';
  // generate html using class="$css_class"...
}

Afterwards, you can specify the colors you want for the alternating divs within your CSS class definitions.

.row_odd { background-color: white; }
.row_even { background_color: #e0e0ff; }

Answer №4

You can achieve this using jquery's :odd and :even selectors in a simple manner:

$(".container div.item:odd").addClass('odd'); 
$(".container div.item:even").addClass('even'); 

http://jsfiddle.net/niklasvh/fULRZ/

Answer №5

.post:nth-child(odd)

Not having any luck with this method?

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

Using jQuery to select a specific checkbox from a group of checkboxes with identical IDs

There is an issue with multiple checkboxes having the same ID in an asp.net repeater control. Users can select either email or phone against each record in the repeater rows. In the example below, there are two rows. If you select the email icon in the fi ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

Tips for rotating a canvas object without changing its position

I am currently in the process of developing a JavaScript game centered around a character positioned on top of the world. Although the earth element is already part of the game, I am encountering an issue with its rotation causing it to shift position as w ...

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

Implement the jQuery colorbox plugin onto a dynamically generated element to display the initial image consistently

Utilizing DataTables.net, I have dynamically created a picture table using ajax. Presently, displaying the pictures through colorbox is functioning flawlessly. $('.colorbox').live('click', function(e) { e.preventDefault(); $(&a ...

Creating a mesh parallel to the xy-plane in Three.js

Looking to brush up on my CG fundamentals. How can I create a mesh (such as a circle) that is perfectly parallel to the xy-plane in the direction the camera is facing? For instance, I want it to be normal to the direction the camera is facing and not tilt ...

Is it true that textarea is not compatible with AJAX .val() or .text() methods?

I'm attempting to utilize AJAX requests in order to transmit textarea data to a google form, however it appears that .val() isn't functioning correctly with textarea specifically. How can I resolve this issue? My goal is to enable individuals to ...

Use ajax to load the script

Encountering a puzzling issue with a script loading function on my IIS local web server. function loadJs(scriptName) { var name = scriptName.toString(); var myUrl = 'http://192.168.1.149/7.0.9.5/m/js/'; myUrl += name; debugger; ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

Center float elements with a percentage width

I am attempting to design a layout in which two elements float alongside each other, starting from the center. I have been successful in achieving this, but only when the width of the two floating elements is fixed. Want to take a look? Follow this link: ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

I need to see the image named tree.png

Could someone assist me in identifying the issue with this code that only displays the same image, tree.png, three times? var bankImages = ["troyano", "backup", "tree"]; jQuery.each( bankImages, function( i, val ) { $('#imagesCon ...

Is it possible to automatically access the most recent Beta build through package.json and npm?

We are currently working on a project that has a specific dependency requirement for the latest beta build from an npm library. However, there are also -dev builds within the library. For instance, in the "x-library" there might be versions like: "1.2.3- ...

Dynamic table in Vue.js updates with saved data when button is clicked

I am looking for assistance on how to work with two or more parameters using Vue.js. I have a data-saving functionality where three inputs are used and the data is saved to a table upon button click. There is an $.ajax() function involved, but I need help ...

What is preventing me from renaming a file in PHP when passed through jQuery?

Hello to all users! I've encountered an issue where I can't seem to change the file name in PHP that is being passed from jQuery: Here is the JavaScript code where I pass the file to the PHP handler: var url = '/temp.php'; var xhr = ...

I'm looking to create a Vuex getter to retrieve data from the Google API documentation – can you help

Can someone help me figure out how to create a getter in Vuex store with flat data from the Google Docs API? My goal is to extract the textRun content and store it in an array because there will be multiple messages. Currently, I have hard coded this respo ...

Using the map function with a React onClick handler

After tirelessly scouring the internet for answers to my query, I've hit a dead end. My goal is to implement a basic react click handler on my button, but for some reason, it just won't cooperate. It's likely something incredibly straightfor ...

Error encountered when injecting Angular module

Currently, I am attempting to develop a sample Angular application with .Net in order to understand how to connect the two technologies. However, I have been encountering an error related to injector::modulerr that I cannot seem to resolve. Despite trying ...

Why is the axios.get promise not getting resolved?

I am currently working on fetching data from MongoDB atlas within a React app. However, despite using .then and .catch with axios.get(), I am encountering an unresolved promise. Here is the code snippet: const entry = axios.get('http://localhost:3001 ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...