Use jQuery to change the background color when clicked

Below is the HTML code with UL and LI elements:

<UL>
<LI><span id='select1'>Text</span></LI>
<LI><span id='select2'>Text</span></LI>
<LI><span id='select3'>Text</span></LI>
<LI><span id='select4'>Text</span></LI>
<LI><span id='select5'>Text</span></LI>
<LI><span id='select6'>Text</span></LI>
</UL>

When clicking on a specific <span>, we want its background color to change. For example, clicking on the span with id='select3' should change its background color.

Please provide guidance on how this can be achieved using jQuery.

Answer №1

Give this a shot:

$('li span[id^="select"]').click(function(){
   $(this).css('background-color',"#ccc")
})

The function of this code is to change the background color when clicking on the span within an li element that has an id starting with 'select'.

Answer №2

Here's a helpful tip for you:

jQuery("#select1").click(function(){jQuery(this).css({'background-color':'red'})});

I hope this solution works for you.

To update my answer and apply the handler to each select element, consider adding an attribute to your span elements to represent color. For example:

<span rel="blue">Text</span>
. Then you can create a handler like this:

jQuery("ul span[id^='select']").click(function(){jQuery(this).css({'background-color':jQuery(this).attr('rel')})});

Answer №3

Experiment with

$("span").click(function(){
  if($(this).attr('id') == "select3") $(this).css('background-color', 'blue');
});

Answer №4

To streamline the handling of multiple list elements, consider utilizing event delegation by only monitoring clicks on the ul. This approach allows you to:

$('ul').click(function(event) {
    switch($(event.target).attr('id')) {
        case select1:
            $(event.target).css('background-color', 'red');
            break;
        //Include additional case statements as needed
    }
});

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

The persistent connection of Socket.io results in consecutive connections while disregarding other occurring events

My goal is to create a unique web application where users can engage in toroidal chess matches with one another. This is the code from my app.js file on the server side: var express = require('express'); var app = express(); var http = require(& ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

Challenge with Redrawing the w2ui Grid

Using w2ui grid (1.4) with angular 1.3.4, I am attempting to display the grid in one view successfully upon first load. However, when I change the view, the grid fails to load and throws an error. ERROR: The parameter "name" is not unique. There are other ...

How can I assign a unique background color to each individual column within a RadioButtonList?

I have an issue with setting 3 repeated columns. I want to assign different background colors to each of them. If you have any ideas on how I can achieve this, please share. Here is the code for my RadioButtonList: <asp:RadioButtonList ID="rblTimeSlot ...

Tips for maintaining the fixed positioning of the left and right flex elements (sidebars) as the middle element scrolls, with the scroll bar located on the right side

I am currently designing a webpage with three main elements: a left sidebar, a right sidebar, and a central feed that is 600px wide and scrolls. The scroll bar must be positioned on the right side of the screen, allowing users to scroll by simply using the ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Is there a way in vee-validate to validate specific sections of a form?

I'm struggling with my English skills. When I utilize 'this.$validator.validate()', I am seeking a way to only validate specific inputs on the page. Is there a method to achieve this? ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

What is causing nested divs to generate a scrollbar?

I am struggling with a situation involving 3 layers of nested divs: <div class="outer"> <div class="inner"><div class="item"></div></div> </div> In this scenario, the .inner div is set to position absolute and each d ...

Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expectin ...

Creating a Regular Expression that excludes all white spaces, including those at the start or end of the string

I attempted to implement this solution, however, I am encountering some issues: Click here to see the demo <form name="myform1"> Valid? {{ myform1.$valid }} <input type="text" name="username1" ng-model="username1" ng-pattern="/^\S.*?&bso ...

Utilizing Props in Vue.js to Access Data for v-model

After browsing online, I attempted to pass props to data in the following manner: Child Component: props: { idInput: { type: String, required: false }, nameInput: { type: String, required: false }, }, data() { return { id: this.idInput, na ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Using JQuery to send an array to PHP and save it to a file

I am currently working on a project where I write test code that posts an array to a PHP page. The PHP page needs to write this array to a file in order to check the data. Here is the JQuery code snippet: $("#Trash").click(function () { $.post("tests ...

Struggling to establish a default value for an AngularJS select dropdown

I'm diving into the world of AngularJS and facing a challenge with setting a default value on a select box. I've successfully listed objects in the select box and binding it to the model works seamlessly. However, as soon as I introduce a default ...

Endless cycle in Vue-Router when redirecting routes

I need advice on how to properly redirect non-authenticated users to the login page when using JWT tokens for authentication. My current approach involves using the router.beforeEach() method in my route configuration, but I'm encountering an issue wi ...

Add some TD(s) after the td element

The HTML code I currently have is as follows: <tr> <td class="success" rowspan="1">Viability</td> <td data-rowh="-Checksum">Viability-Checksum</td> </tr> <tr> ...

Tips for optimizing caching of API responses and assets using service workers in Vue CLI 3

import { register } from 'register-service-worker' import pwa from '@vue/cli-plugin-pwa' if (process.env.NODE_ENV === 'development') { // if (process.env.NODE_ENV === 'production') { console.log(pwa) register(`${pro ...

Struggling to implement JQuery code in a Next.js application

I'm having trouble getting my tracking code to work in Next.js. <Script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments) } gtag('js', new Date()) ...