How can we target every nth child element universally?

I am working with an HTML structure that has a specific layout, and I need to target all odd <span> elements globally without considering their parent elements.

Is there a way to style 1, 3, 5, 7, 9 in red color? I attempted to use :nth-child(odd) but it seems to work locally only.

body {
  counter-reset: spans;
}

span {
  counter-increment: spans;
}

span::after {
 content: counter(spans);
}
    
 span:nth-child(odd) {
   color: red;
}
<div>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

Answer №1

Sorry, but the :nth-child() and :nth-of-type() selectors do not work in the way you are thinking:

  • :nth-child(expr) only selects elements based on their position within their immediate parent element that meets the criteria of expr, not their position in the overall document or any other ancestor.
  • :nth-of-type selects elements based on their position among siblings that meet the condition specified by expr. This means it does not consider elements outside of its own sibling elements in the DOM tree.
  • Therefore, what you are trying to achieve cannot be done solely with CSS selectors as there is no :nth-overall or :nth-of-type-overall pseudo-class available.
  • You can accomplish this by using client-side scripting to add specific classes to those elements manually when the page loads.

For example, something like this:

const allSpans = document.getElementsByTagName("span");
for( let i = 1; i < allSpans.length; i += 2 ) {
    allSpans[i].classList.add( 'isGloballyOdd' );
}
body {
  counter-reset: spans;
}

span {
  counter-increment: spans;
}

span::after {
  content: counter(spans);
}
    
span.isGloballyOdd {
  color: red;
}
<div>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
</div>
<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

This implementation would result in something like this:

https://i.stack.imgur.com/nHGsr.png

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

Performing two consecutive nested AJAX requests in jQuery using JavaScript

I am facing an issue with my code. My goal is to create a cryptocurrency ranking feature on my website. I have integrated an API that provides logos, symbols, indices, prices, etc. of cryptocurrencies. However, I encountered a problem as this API doesn&apo ...

Will the bootstrap carousel continue running in the background even if I hide it?

Currently, I have incorporated the twitter bootstrap carousel into my website with the following code: <div id="slider" class="carousel slide"> <!-- Wrapper for slides --> <div class="caro ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

Differences in Cross-Browser Styling for ListView Item Templates

I'm following up on my previous query regarding ListView's ItemTemplate table styling. I am still working on achieving the desired look for the ItemTemplate: ______________________________________________ | |___________Title_______ ...

Issues with Vertical Alignment and Navigation

Link: Please resize the browser to mobile view. Issue with Header: I am facing alignment issues in the header. The elements do not seem to be aligned properly at the center of the header. The Android logo is aligned, but the text and dash image are not. ...

I have successfully implemented a click effect on one image and now I wish to apply the same effect to the remaining images

I've exhausted all my options and still can't crack this puzzle. Let me break it down for you: Upon entering the page, users are greeted with a collection of images each tagged with classes (for example, img01 and img02). When an image is clicke ...

Switching JSON data when clicked in Angular 2

Looking for a way to dynamically switch between different data sets in JSON upon user interaction with UI buttons. I am utilizing Angular 2 framework for this task. The HTML structure is as follows: <button type="button" (click)="changeOdds('odds ...

Activating scrolling through Javascript

A friend of mine created a web page to help me learn some JavaScript. He designed a feature where the content in each div becomes visible as soon as the user scrolls past it. However, I noticed that the content appears too late for my liking. I would like ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

Drupal 6 encountering an inline AJAX error

Is there a way to add custom inline error messages to a form in Node, including CCK and other elements? I have looked at multiple modules, but none of them seem to offer a complete solution as they lack CCK support, upload support, error messages, etc. ...

What is the process of utilizing a <li> for a hover selector in jquery?

I've encountered an issue with a list that I am trying to modify its content when hovering over them. Despite using the id as a selector for triggering the hover function, all list items change color instead of just the intended one. The challenge lie ...

What is the best way to retrieve the content of a file and set it as the value

exam.php <div class='btitle'>LOREM</div> main.php <?php $content = file_get_contents('exam.php'); ?> <textarea class='txa' value = <?php echo $content; ?>></textarea> outcome text ...

Click on another part of the page to reveal a dropdown menu

I am seeking a way to trigger the opening of this dropdown select not by directly clicking on its position, but rather by clicking on another <span>. Displayed below is the dropdown menu: <div class="styled-select"> <span id="camDurati ...

Organizing the website's files and extensions

Transitioning from programming desktop applications to websites can be overwhelming, especially when dealing with multiple languages and extensions like JavaScript, CSS, JSON, Bootstrap, Ajax, and PHP all at once. How do you effectively juggle these diff ...

Can a class be created using a PHP variable as its basis?

Is it possible to define the body color based on a variable in PHP? I have been experimenting with different methods to achieve this. <?php $seperate_sitting_yes = "Yes"; if($seperate_sitting_yes == "Yes") { ?> <style type="text ...

Create text that alternates between blinking and changing content simultaneously

I'm currently working on a website and I am curious about how to achieve the effect of making text blink and change content simultaneously, similar to what is seen on this particular website . Sorry for not being more specific in my question. Thank yo ...

Including CSS in an HTML file does not function properly

I've been attempting to import a CSS file into an HTML document, but for some reason it's not working. I have also tried linking the path directly, but that hasn't worked either. <!DOCTYPE html> <html lang="en"> <head> < ...

Using the Play framework to showcase data in an HTML table

I have a project where I am working with multiple tables, one of which is a Person table containing id and name attributes. I have successfully retrieved the data from the database using MySql and converted it into JSON. However, I am struggling to find a ...

The most effective way to align text in a right-to-left language is by utilizing the text-align property with a

If the project is in a right-to-left language (such as Persian or Arabic), which method is preferable for setting text-align: right and direction: rtl? Option 1: Implement globally, for example: body * { direction: rtl; text-align: right; } ...

Adjust the height of an element when the maximum height is set to none

I am trying to add animation to the opening of a menu on my website. This is achieved by adjusting the max-height property of the <div> element that represents the menu, as well as changing the display property. The max-height value is being changed ...