Is there a problem with using Nth-Child / Nth-Of-Type in CSS when classes are dynamically added or removed using jQuery?

Currently, I have a set of LI tags. As users filter the LIs, some may be removed from view. My goal is to assign alternating background colors to the visible LIs.

When an LI is visible, it is given the class "LI-Shown." If an LI gets filtered out, I remove the LI-Shown class.

After filtering, my HTML could look like this:

<ul id="LI-List">
 <li id="1" class="LI-Shown">Showing</li>
 <li id="2" class="LI-Shown">Showing</li>
 <li id="3" style="display:none">Was Filtered Out</li>
 <li id="4" class="LI-Shown">Showing</li>
</ul>

This is my current CSS code:

.LI-List .LI-Shown:nth-child(even) {
  background-color: gray;
}

The alternating background works when all 4 LIs are visible or initially loaded. However, after filtering down, both the 2nd and 4th LI have gray backgrounds, even though the 3rd LI has been removed from view along with its LI-Shown class.

What should happen is that only the LI-Shown classes (IDs 1, 2, and 4) should be displayed, and only ID = 2 should have a gray background.

I am struggling to find a way for the CSS to treat the 4th LI as if it were the 3rd LI-Shown class. It needs to revert to its default background color instead of staying gray.

In addition to CSS, I also attempted to utilize jQuery directly using the following code:

$('.LI-List .LI-Shown').filter(":even").css('background', 'gray');

Any assistance would be greatly appreciated. Thank you!

Answer №1

  1. When using a <ul> element, remember to use the attribute class instead of id. For example: <ul class="LI-List">
  2. Nth-Child and Nth-Of-Type selectors cannot be applied to classes. Nth-Child selects based on DOM hierarchy, while Nth-Of-Type targets specific tag types (p, div, span, etc.)
  3. Here is a jQuery solution:

$('.LI-List .LI-Shown').filter(":even").css('background', 'gray');
.LI-Hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="LI-List">
 <li id="1" class="LI-Shown">Showing</li>
 <li id="2" class="LI-Shown">Showing</li>
 <li id="3" class="LI-Hidden">Was Filtered Out</li>
 <li id="4" class="LI-Shown">Showing</li>
</ul>

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

Populate jQuery datatable using an XML response

I received an XML response from my webservice: <TABLE> <ROW> <ID>1</ID> <SEARCHKEY>XYZ</SEARCHKEY> <SUBURB>XYZ</SUBURB> <RATING>NA</RATING> <DELIVERY>sss</DELIVERY> <STATE>XYS& ...

Leveraging jQuery for Custom Form Styling

.I prefer to utilize personalized form elements in my forms. <fieldset> <legend id="Cities">Urban Areas</legend> <div class="legend-underline"></div> <div class="filters" id="Cities-filters"> <div> < ...

Tips for automatically hiding a button when the ion-content is being scrolled and displaying it again once scrolling has stopped

I have implemented a scroll function event in my HTML file using the following code: <ion-content (ionScroll)="scrollFunction($event)"> <ion-card *ngFor="let product of products" no-padding> <ion-item class="bigclass"> <i ...

Positioning icon/image beside the input box

Currently, I have a form with two buttons in a row and an icon (paper clip) that I am attempting to align next to the buttons using UIKit. However, I am facing challenges in getting the alignment right without affecting the size of the elements. Below is a ...

The quantity addition and subtraction function is malfunctioning

I have implemented a quantity plus/minus feature in HTML which is embedded from a jQuery script provided below. jQuery.ajax({ type: "POST", url: "http://ayambrand-com-my-v1.cloudaccess.host/index.php?option=com_echa ...

The sidebar made an unexpected leap from one side to the other, with no memory of ever tampering

I'm feeling a bit overwhelmed because I can't seem to figure this out. My goal is to create a basic page layout with a header, subheader, sidebar, content pane, and footer. Everything was going smoothly until I started writing a function in my J ...

Comparison of loading time between loader gif and browser's loading image

Recently, I've come across a code snippet where I implemented a 'loader' gif to show while PHP retrieves data from an SQL database. Everything seemed to be working fine when testing on my localhost. However, upon closer observation, I notice ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Utilizing Gulp variables to create dynamic destination file names?

As a newcomer to gulp, I am curious about the feasibility of achieving my desired outcome. Here is the structure of my projects: root | components | | | component_1 | | styles.scss | | actions.js | | template.html | | ... | componen ...

Tips for Styling "Opened" Elements within the <Summary><Details> Web Design in HTML using CSS? (a color coding challenge)

I've dedicated a significant amount of time crafting my ultimate HTML FAQ with detailed summaries styled in CSS. There's one aspect that continues to elude me - achieving the perfect orange background color for expanded topics: My goal is for a ...

What is the best way to align this content in a specific area?

How can I center the content in each section of my webpage? Here is an image for reference: https://i.stack.imgur.com/PHEXb.png I want Section 1 and Section 2 to be 100vh with the content centered on the page. .content { height: 100vh; } <!do ...

Perform the function with the value of the currently selected option

Despite selecting an option, a message still appears stating "Please choose something." This function works with only one dropdown list, but encounters issues when there are two or more. (In this example, the variable 'sport' is document.getElem ...

The disappearance of data stored in .data() in JQuery

I've encountered an issue with a function that creates an anchor, stores data, and appends it to a div element. var x = $("<a class='randomclass'></a>"); x.data('foo', 'bar'); console.log(x.data()); ... $("&l ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

HTML and JQuery Image Slide Show

Help! I'm struggling with this image slider that's meant to showcase images fading in and out every 5 seconds. Being a beginner in coding, I could really use some assistance with getting it to work properly. Currently, I'm stuck on the firs ...

What is the best way to capture a screenshot of a website using its URL?

I've been curious about the possibility of capturing a screenshot of a remote website using only a URL and some JavaScript code. This functionality is often seen on bookmarking sites. I can't help but wonder if this is achieved through a virtual ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Developing dynamic 3D cubes

In my latest project, I am attempting to construct a unique structure composed of 3D cubes arranged in a stacked formation. Each of the individual cubes within this structure is designed to be interactive for users. When a user hovers over a cube, it trigg ...

Stop multiple form submissions using jQuery Mobile's Ajax Navigation feature (without turning off Ajax)

Whenever I quickly click the Submit button on my form, it results in two successful AJAX posts. How can I prevent this duplication? Upon further investigation, here is what seems to be happening: User clicks submit Ajax post sent User clicks submit (com ...

Function being called once more upon completion of Ajax request

Is there a way to ensure that a function is called again only after the completion of an AJAX request, specifically if a button was pressed while the AJAX request was in progress? $(document).ready(function(){ $_button.on('click',function(){ ...