Strategies for identifying specific children in my particular situation

Here's a snippet of my code:

<ul id='nav'>
            <li><h1 id='unique' class='title'>Topic</h1></li>
            <li><h1 class='toptitle'>Department</h1></li>
            <li><a  class='title' href='#'>test1</a></li>
            <li><h1 class='toptitle'>test2</h1></li>
            <li><a  class='title' href='#'>test1</a></li>
</ul>

I'm trying to change the background color of the li items when a user clicks on them, but I want to keep the '#unique' item's background unchanged.

This is what I have so far:

$('.title').on('click', function(e){
      $(this).closest('ul').find('li').not('#unique').css({'background-color':'white'})  //change all li backgrounds except for the first one
      $(this).parent().css({'background-color':'#DDDDDD'})
})

However, my current code doesn't seem to be working as intended. Can someone help me figure out how to change all li backgrounds except for the first one? Thank you!

Answer №1

The reason is that the id is not located on the li element, but rather on a child element. You can utilize the has selector to locate it.

.not('#unique')

transforming into

.not(':has(#unique)')

JSFiddle link

Answer №2

To omit the initial child element, you can utilize the selector :first-child

$(this).closest('ul').find('li').not(':first-child').css({'background-color':'white'})

JSFiddle

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

"Customizing the properties of an Angular Material mat-slide-toggle: A step-by-step

<mat-slide-toggle>Slide Me!</mat-slide-toggle> https://i.stack.imgur.com/p1hzD.png https://i.stack.imgur.com/aCzs1.png Is it possible to customize the toggle-thumb-icon to increase its length and position it at the end of the bar? ...

sending information back to the controller with get method (ajax, javascript)

I'm currently facing a challenge where I have an event listener waiting for a button to be pressed. Once the button is pressed, the controller method 'update' is called which then triggers the view method 'input' to fetch data from ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Error: jwt_decode function has not been declared

I'm currently working on a project and I've hit a roadblock while trying to fetch profile information for the logged-in account using a token. Despite using the JWT-decoding library, I keep encountering the issue where jwt_decode is not defined. ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Displaying API logs on an Html console

function updateData(e) { const animeName = e.target.value; const apiUrl = `https://nyaaapi.herokuapp.com/nyaa/anime?query=${animeName}`; fetch(apiUrl) .then((res) => res.json()) .then(displayAnimeData); } const inputField = document.getEl ...

Transforming a string representation of a nested array into an actual nested array with the help of JavaScript

My database stores a nested array as a string, which is then returned as a string when fetched. I am facing the challenge of converting this string back into a nested array. Despite attempting to use JSON.parse for this purpose, I encountered the following ...

Extracting specific keys from JSON data

I am working with an array named cols: var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic The JSON data is coming from the backend as: info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84} If I want to sel ...

The buttons within the bootstrap navbar are not properly collapsing or resizing when the screen size is decreased, causing them to overlap and maintain their

As a newcomer to bootstrap, I recently created a navbar with several buttons. However, when I reduce the screen size to 1000 pixels, the button text gets overwritten and the navbar extends off the screen. I don't want the navbar to collapse at this si ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Receive a notification when the div element stops scrolling

I am attempting to replicate Android's expandable toolbar within an Angular component. My HTML code appears as follows: <div (scroll)="someScroll($event)"> <div class="toolbar"></div> <div class="body"></div> </d ...

Sleek and versatile sidebar reaching full height

Is there a way to make my sidebar cover the full height of the screen without using position: fixed? The code I've tried doesn't seem quite right. Any tips? JSFindle: http://jsfiddle.net/Pw4FN/57/ if($(window).height() > $('#page-contai ...

Is there a way to combine two addEventListeners into one for a single click event?

preview of a to-do list app I am faced with a situation where I have two addEventListeners, one to change the text color and another to change the circle color. In Condition 1: When I click on the circle, both the text and circle colors are changed. In ...

How to completely color a div in CSS

<h:head> <title>Unique Title</title> <style> .top{ margin: 0; padding: 0; background-color: blue; height: 15px; width: max-content; } </style ...

Having trouble getting Ajax post to function properly when using Contenteditable

After successfully implementing a <textarea> that can post content to the database without needing a button or page refresh, I decided to switch to an editable <div> for design reasons. I added the attribute contenteditable="true", but encounte ...

Could it be true that Html.ValidationSummary establishes a specific property?

Is there a way to determine the presence of Html.ValidationSummary in code without relying on specific HTML tags? For instance, when using Html.ValidationSummary(true), the tag div class="validation-summary-valid" may not be present. This makes it difficul ...

Attempting to locate the element's position using Selenium in Python

quem_esta_sacando = driver.find_elements_by_xpath("//div[@class='gameinfo-container tennis-container']/div[@class='team-names']/div[@class='team-name']") this is how I located the correct class, but now I want to ...

Modifying an object's value before pushing it into an array in JavaScript

I've been struggling to find the right keyword to search for my issue. I've spent hours trying to figure out what's wrong, but it seems like a simple case of pushing an object into an array. The problem arises when I try to log the values of ...

Is it possible to utilize the <hgroup> element with various <h> heading levels?

<hgroup> <h4>Role</h4> <h3>Graphic Designer</h3> <h5>Company: Godigital</h5> </hgroup> Should I keep this structure, or should I use the <h3><h4><h5> order instead? ...