Using CSS to apply alternating colors to span elements within children

My DOM structure is generated by a JS framework and may appear like this:

span:nth-child(odd) { background-color: lightblue; }
span {
    display: block;
}
<div id="parent">
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>

  </div>
  <div class="child">
    <span>Some text to color in alternate colors</span>
  </div>
</div>

I am attempting to alternate the color of the spans regardless of whether the parent element is the same or not. I have tried using pseudo selectors and referencing a question on CSS div alternating color, but had no success. Is achieving this solely with CSS possible, or should I consider a solution involving a JS framework?

Answer №1

It is unlikely that a CSS-only solution will work across all browsers, so I suggest incorporating a bit of JavaScript.

By using the querySelectorAll() method provided by the Document interface, we can retrieve a collection of elements that match a specific selector.

For example, to select all <span> elements:

document.querySelectorAll("span")

We can then convert the returned HTMLCollection into an array and apply filters to target even or odd elements. Subsequently, we can add a CSS class to these elements using the element.classList.add() function.

Array.from(document.querySelectorAll("span")).forEach((element, index) => {
  if (index % 2 == 0) {
    element.classList.add("background");
  }
})
.background {
  background-color: lightblue;
}

span {
  display: block;
}
<div id="parent">
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
    <span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
  </div>
  <div class="child">
    <span>Some text to color in alternate colors</span>
  </div>
</div>

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

Removing or hiding elements using jQuery

My HTML code includes a select tag, and when the value changes, I want to retrieve data from the database based on this new value. The data is then displayed in a new div. This new div contains a close sign that should hide the div when clicked by the user ...

When you tap on the child element, ignore the parent element

Is there a way to make CSS understand that clicking on a child element within the parent should not be considered as clicking on the parent as well? Why not give it a try by clicking on one of the children inside the parent? .parent{ background: b ...

What is the best way to incorporate a text box along with a submit button that triggers a callback to a javascript function when clicked, utilizing either plain javascript or jQuery?

As a beginner in the world of JavaScript, I'm struggling to find the solution to this problem. Any assistance would be greatly welcomed. ...

Forget the function once it has been clicked

I'm looking for a solution to my resizing function issue. When I press a button, the function opens two columns outside of the window, but I want to reset this function when I click on another div. Is there a way to remove or clear the function from m ...

Tips for adding an svg element to an existing svg using d3.js

Can another SVG be appended to an existing SVG parent using d3.js? I have tried using the 'svg:image' attribute, but unfortunately, I lose full control over the inner SVG child. The DOM node is created by d3, but it is not rendered, resulting i ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

What is the best way to apply styling to a kendo-grid-column?

Utilizing the kendo-grid in my project serves multiple purposes. Within one of the cells, I aim to incorporate an input TextBox like so: <kendo-grid-column field="value" title="{{l('Value')}}" width="200"></kendo-grid-column> It is ...

Seamless animation when collapsing element using angular and css exclusively

I am attempting to incorporate a collapsible feature into my application. Rather than relying on external libraries like jQuery, I want to exclusively utilize Angular. For demonstration purposes, I have created a very basic example here: http://jsfiddle.n ...

What is the best way to retrieve a variable in AngularJS1 after the HTML has been divided into multiple child HTML files?

I have segmented my main HTML page into multiple subpages and included them in the main file. However, it seems that each subpage is referencing different '$scope' variables. I am trying to reference ng-modle="My-model" from one subpage to anothe ...

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Tips on adjusting the dimensions of a switch in kendo UI angular with CSS

Currently, I am utilizing angular in combination with Kendo ui. Is there a way to modify the dimensions of the switch button in Kendo UI Angular using CSS? ...

Utilizing a CSS file within a YAML configuration in R Quarto

Is there a way to reference a css file from a yaml file in my R Quarto Book? The css file defines the theme for my Quarto document, and I want all our Quarto docs to have the same appearance. When I directly call the css file, I can customize aspects like ...

Changing CSS properties in React

Currently, I am working on a dynamic table component using CSS grid. My goal is to customize the grid-template-columns CSS property. I am familiar with using repeat in CSS to achieve this. However, I am facing a challenge when it comes to dynamically chang ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

The variable $_FILE fails to retrieve the file, resulting in PHP displaying an undefined variable error

I am facing an issue where I am unable to get the image file sent from an HTML form to insert it into a database. The other variables are being posted successfully, as I have checked them by echoing, but the image file is not getting posted. I suspect that ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

Convenient method for extracting the final element within a jQuery section

I need to determine whether the div with the class "divclass" contains an anchor tag. If it does, I have to run a specific block of JavaScript code; otherwise, no action is required. <div class="divclass"> <span> some text</span> ...

I am having trouble getting my custom CSS file to be applied to my website on Github pages

I attempted to upload a custom CSS file to apply on The raw CSS file is located at: https://raw.githubusercontent.com/themomoravi/SoundOff-Website/master/styles.css I used the following as my href since it directly links to the raw CSS file: href="http ...

Update the icon within the expandable display

Is there a way to change the plus sign to a minus sign in an expandable table view on click? (changing fa fa-plus to fa fa-minus) The goal is to have the plus sign displayed when the view is compressed and the minus sign displayed when it is expanded. If ...