What is the best way to apply the :nth-child() selector to target every second <div> element within ALL child elements?

I'm currently developing a commenting feature, and I am in need of CSS to select every alternate child <div> (even children nested within the first set of children).

Consider this example HTML structure:

 <body>
<div class="comment">
    <div class="comment"/>
    <p class="something else"/>
    <div class="comment">
        <div class="comment"/>
        <div class="comment"/>
    </div>
</div>
<div class="comment"/>
<div class="comment"/>
</body>

How can I target every other <div> within the body excluding <p> tags?

The desired outcome should have the following pattern:

(Double asterisks signify even, single asterisk denotes odd, no asterisks indicate neither)

 <body>
    **<div class="comment">**
        *<div class="comment"/>*
        <p class="something else"/>
        **<div class="comment">**
            *<div class="comment"/>*
            **<div class="comment"/>**
        </div>
    </div>
    *<div class="comment"/>*
    **<div class="comment"/>**
    </body>

I aim to style every other <div> systematically.

Is there a solution for achieving this?

Answer №1

- Interactive demo showcasing threaded comments with colors
- Basic demonstration

It took some time to comprehend that the terms "even" and "odd" do not refer to CSS's predefined classes, but instead indicate the position order of a .comment div, whether nested or not.

Implementing this concept purely through CSS is extremely challenging, if not nearly impossible, without convoluted styling rules to cover all scenarios.

However, achieving this functionality with jQuery is much simpler:

$('.comment').addClass(function(i){
  return i%2 ? "odd" : "even";
});

In this code snippet, the variable i signifies the index position (0, 1, 2, 3...) of each collected .comment element in jQuery's selection process. If i modulus 2 results in 0, the "even" class is added; otherwise, the "odd" class is assigned to the element.

CSS:

div.comment{
  /* Common styles */
  color:#fff;
  margin:5px;
  border:1px solid #000;
}
.even { background:blue; } /* Odd Indices: 0, 2, 4, 6, 8... */
.odd  { background:red;  } /* Even Indices: ...1, 3, 5, 7... */

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

What is the best way to halt the ticking of this clock in JavaScript?

I can't seem to figure out how to stop this clock using JavaScript Even though I press the stop button, the clock keeps running <!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to halt the clo ...

when a div contains another div and is then followed by another div, apply the following style

Is there a way to create a rule that functions like the following: .container .unit:first-child(if it contains div.box1.extra) + .box2 { top: 50px;} <div class="container"> <div class="unit"> <div class="box1 extra"><!-- co ...

Why isn't the image showing up as a list style?

I can't seem to get the image to show up on my page. Can anyone help me figure out what's wrong? ul li { background-image: url(logo.png); background-repeat: no-repeat; padding-left: 0px; } This is what I'm currently seeing: This is what ...

What could be causing this unexpected delay?

I have been working on improving the load time of my website as it was quite lengthy, but even after optimizations, I am facing issues specifically with the jQuery UI CSS images. If you could spare a moment, would you mind taking a look at this Pingdom te ...

Arrange a div within a list element to create a grid-like structure

My current structure is as follows: <ul class="wrap-accordionblk"> <li class="accordionblk-item"> <div class="accordionblk-header"> <div class="row-fluid"> <div class="infoblk"> <label>SESSION ID ...

A guide to extracting data from HTML tables using Python for web scraping and exporting the results to

My Python skills are still pretty basic, but I'm working on creating a web scraping tool to extract data from an HTML table online and save it into a CSV file with the same structure. Here's an example of the HTML table (I'll show just a fe ...

Remove the pop-up using its unique identifier, element, or style class

I recently launched a free hosting site, but I'm encountering an issue where an ad for the site keeps appearing upon loading. I need to find a way to remove the specific rows that contain this ad. Specifically, I want to delete the ****BOLD**** rows, ...

What is the best way to display a success notification when a transaction is successfully executed in web SQL

var brand = "Glare"; var price = "3000$"; var color = "blue"; var success = tx.executeSql("INSERT INTO truck (brand, price, color) VALUES ('"+brand+"','"+price+"','"+color+"' ")"); if(success) { alert("successfully insert ...

Seeking Assistance with Customizing HTML Uniform Panels

Looking at the HTML provided, I have two requirements: Request: I need to center the green boxes regardless of their height, without having to adjust the top:-10px/bottom:-10px values when the height changes. Eliminate the fixed top/bottom value (as the ...

Gaining a comprehensive understanding of media queries

Hello everyone, I need some help with media queries. I've been working on a website that is already responsive. However, I am required to write the code in a child theme rather than directly in the original files. When I attempt to add new media quer ...

Add a specific CSS class to a div element depending on the status of a checkbox

Is there a way to dynamically append data based on the selected items in a checkbox table? I want to be able to add multiple or single items by clicking the add button. The key is to avoid appending duplicate data that already exists in the view. Any sugge ...

I can't figure out why my code isn't functioning properly. My goal is to have a PDF file generated when the submit button is clicked on a form, and for a

Hello everyone, I am new to the world of programming, but I have been assigned a project that involves using jQuery, JavaScript, html2pdf, and Bootstrap 5. I seem to be facing some issues with my code. Can someone please help me identify what's wron ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

css absolute positioning and setting the height of a repeating background

I am facing a challenge with a container that contains a repeating image and I want it to fill 100% of the available height. However, some inner divs have their :after pseudo elements absolutely positioned to achieve the desired borders, which is causing a ...

What is the best way to handle images overflowing a div

I am currently working on creating a carousel using React, where the content images are aligned horizontally. If I have 3 image tags within a div with a width of 1200px, how can I effectively control these images to ensure they fit within the container div ...

Is there an issue with this html code?

Can you help me troubleshoot this HTML code snippet I have? <html> <head> <script type="text/javascript" language="JavaScript1.3" src="js/euDock.2.0.js"></script> <script type="text/javascript" language="JavaScript1.3" ...

How to Override Global CSS in a Freshly Created Angular Component

My CSS skills are a bit rusty and I need some assistance with a project I'm working on. The project includes multiple global CSS files that have properties defined for different tags, such as .btn. However, these global CSS files are causing conflicts ...

When using IE8 with pie.htc, implementing html5shiv.js causes rounded corners to disappear once more

While everything is running smoothly in most browsers, there seems to be an issue with IE8. After connecting pie.htc to address the rounded corners problem, everything seemed fine until html5 issues cropped up in IE8. To combat this, I implemented html5shi ...

What is the best way to include PHP code within an HTML tag?

I need help figuring out how to display the value of a variable called 'fname' inside an HTML tag. Below is a snippet of my code where I'm trying to get the input value and print it in a paragraph tag. <?php if (isset($_POST['submit ...

When using CSS @media print with inches, different dimensions are displayed post-printing

I'm currently working on a project that involves printing a single div from my webpage. However, I've encountered some issues with the @page tag not affecting the print output as expected. I attempted to manually set the dimensions of the element ...