Modify the color of a set of div elements when clicked

Is there a way to change the background color of all divs with a common attribute value (#id for example) after clicking on one of the divs that shares the same attribute value?

This is what I have tried so far:

$('.group').click(function(){

  var clickedID=$(this).attr("id");
    $('.group').(function(){
        if($(this).attr("id")==clickedID){
          $(this).css({"background-color",'red'});

          });
      ;

  });

Answer №1

To avoid having multiple ids with the same name on a page, it is recommended to use classes instead.

if( $(this).hasClass('classname') ) { ... }

In document languages, attributes declared as type ID are unique and cannot have the same value. This uniqueness allows an ID attribute to identify its element uniquely. In HTML, all ID attributes are named "id," while XML applications may use different names for ID attributes but still have the same restriction.

For more information, visit: w3.org

Answer №2

It seems like many people were focused on the issue of duplicate IDs, which is a valid concern, but not the main point of the question. You just happened to choose the one attribute that can't be repeated.

Your code structure is solid:

  1. Attach a click event to all .group elements
  2. On click, retrieve the attribute value of the clicked element
  3. Find elements with the same attribute value and modify the CSS

Choosing the attribute for linking

If using the same id is not an option, HTML5 introduced a solution known as the data- attribute. According to MDN:

data-* attributes allow us to store extra information on standard, semantic HTML elements, providing a way to associate data with an element without defining its meaning.

In this case, you can use data-value to link elements like this:

<div data-value="x" class="group">1</div>
<div data-value="y" class="group">2</div>
<div data-value="x" class="group">3</div>

Here, elements 1 and 3 are connected.

Retrieving the value and associated elements

JQuery provides a convenient method, .data(), to access these values. Simply use it like this:

var clickedValue = $this.data("value");

To find associated elements, search for .group elements with the same attribute value using the attribute equals selector:

$('.group[data-value="' + clickedValue + '"]')

Adjusting the CSS

Once you have identified the elements, utilize .css() to alter the background color. It takes either two strings for a single CSS property or an object for multiple properties. Since we only want to change background-color, the former method will suffice:

someJQueryObject.css('background-color', 'red');

Putting it all together

Now that we have the steps in place, all that's left is to combine them. I've also included a line to store the jQuery object for $(this) to show how it can be utilized. While it's not necessary in this case since it's only used once, it illustrates the concept.

$('.group').click(function () {
    // This "caches" the jQuery object, making it more efficient if used multiple times
    var $this = $(this);
    
    // Retrieve the "data-value" of the clicked element
    var clickedValue = $this.data("value");
    
    // Find other groups with the same data-value and apply the CSS
    $('.group[data-value="' + clickedValue + '"]').css('background-color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div data-value="x" class="group">1</div>
<div data-value="y" class="group">2</div>
<div data-value="x" class="group">3</div>

Answer №3

Alright, let's break down what you're attempting to achieve.

Function

The way you're using .(function is quite off. It seems like you're trying to validate the clicked item against a specific ID. You should declare that ID as a variable outside the function like this:

var validID = 'foo';

Then create a separate function for validation:

function checkID(id, $el){
    if (id === validID){
        $el.css({
            backgroundColor: 'red'
        });
    }
}

jQuery

Now, incorporate this function into your .click() event:

$('.group').on('click', function(){
    var self = this;

    checkID(self.id, $(self));
});

Result

Your final JavaScript code should look something like this:

var validID = 'foo';

function checkID(id, $el){
    if (id === validID){
        $el.css({
            backgroundColor: 'red'
        });
    }
}

$('.group').on('click', function(){
    var self = this;

    checkID(self.id, $(self));
});

Additional tips to consider:

  • Prefer using === over == as it checks both value and type, ensuring more accurate comparisons.
  • Utilize element properties like this.id for better performance compared to jQuery functions like $(this).attr('id').
  • Cache elements or objects you need to reference multiple times for improved speed and resource efficiency.
  • Switch to using .on() instead of shorthand event binding for better maintenance and performance.

Instead of:

$('.someSelector').click(function(){
    // stuff
}).mouseenter(function(){
    // stuff
}).mouseleave(function(){
    // stuff
});

You can use:

$('.someSelector').on({
    click: function(){
         // stuff
    },
    mouseenter: function(){
        // stuff
    },
    mouseleave: function(){
        // stuff
    }
});

This approach is both easier to manage and faster as it reduces DOM traversal.

Hopefully, this information is beneficial to you!

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

Leveraging Angular's catchError method to handle errors and return

One of my challenges involves a model class that represents the server response: class ServerResponse { code: number; response: string; } Whenever I make api calls, I want the response to always be of type Observable<ServerResponse>, even in ...

Accessing a resource file from a compiled JAR archive

One issue that I am facing involves the project structure of my Maven Java project. It follows a typical layout: src/main/java - project .java files src/main/resources - project resources (log4j2.xml) src/test/java - .java files for tests src/test/r ...

AngularJS controller encounters a scoping problem within a callback function

I have created an angular application with a simple login form that can be viewed on this JSFiddle. HTML Code: <form data-ng-app="jsApDemo" data-ng-controller="loginCtrl"> <label for="username">Username:</label> <input type=" ...

Tracking the completion percentage of an asynchronous request using Chunked Transfer-Encoding

Is it feasible to retrieve the percentage status of an Ajax GET request (utilizing jQuery) in situations where the header does not specify Content-Length? I am implementing Transfer-Encoding: Chunked rather than Content-Length. ...

Organizing content with divs in HTML/CSS

I've incorporated a theme in my designs where there is a blue bar beneath the text, like shown in the images below https://i.sstatic.net/TuVGd.png https://i.sstatic.net/CCJRo.png Currently, I've been structuring my HTML for these bars in the f ...

Rails - Issue with jQuery/AJAX causing partial not to refresh

Currently, I have a timeline view that displays event partials, allowing users to create, read, update, and delete events directly on the timeline. However, I am facing an issue where the delete partial does not refresh after deleting an event, requiring t ...

Ways to transition to the subsequent page in Selenium WebDriver following the click of the submit button

https://i.sstatic.net/QWcHm.jpg After successfully automating the process of filling in a textbox and clicking the "proceed with booking" button using a submit() command, I encountered an issue. The HTML code does not provide a URL that can be used in the ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

The functionality of the Bootstrap dropdown list button is not functioning properly on mobile devices

Currently, I am in the process of developing a website and testing its mobile view on my iPhone. The website is still using bootstrap 3, but I have encountered some issues. When I tap on the navigation button on my iPhone, nothing happens - no dropdown lis ...

Ways to incorporate the setTimeOut function

<body> <script> $(window).scroll(function() { $('#csgo').each(function(){ var imagePos = $(this).offset().top; var topOfWindow = $(window).scroll ...

Django not receiving data from AJAX GET request

I am attempting to transmit data stored in localStorage through an AJAX GET request to Django, but the Django server does not seem to receive it. I have verified that there is data in localStorage("preselection") as indicated by the output of console.log. ...

Having trouble with my basic jQuery Ajax call not functioning as expected

When accessing this URL http://schooltray.com/VsStWsMblApps/SayHello?fullName=Joe%20Smith The response is: {"SayHelloResult":"{\"Status\":1,\"Message\":\"Hello Joe Smith\"}"} However, my JQuery call seems to be failing. Bel ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Issue with Jquery navigation toggle class not functioning properly following a link click

I am facing an issue with my navigation that consists of links with either the "active" or "inactive" class. I have written a jQuery script where, when a link is clicked, the last active one becomes inactive and the clicked one becomes active. However, the ...

Error code "ER_BAD_FIELD_ERROR" was encountered with errno 1054 and sqlState "42S22" in index 0 while using MySQL with Angular and managing sessions

When I log in, the following code is executed: <div ng-include="'partials/navbar'"></div> <form name="form" ng-submit="login(form)"> <div> <input type="text" placeholder="Email" ...

What is the process of converting exactPageList from any to any[] before assigning it to pagefield?

Encountering an issue with paging on my angular 7 app where I am unable to assign exactpagelist of any type to pagefield of type array. The problem seems to be occurring on the last line of the function totalNoOfPages at this point: this.pageField = this ...

Python file is not able to show data on HTML table

I am having difficulty displaying the data retrieved from the database in an HTML table. store.py def book_list(): # Define the query for the DB query = "SELECT * FROM " + DBtable` ## Execute the query mycursor.exe ...

onkeypress() method not triggering the function

I have a task to prevent users from typing "%" in a textArea, so I implemented the following: However, even after clicking inside the text area, I can still type '%', indicating that my onkeypress function is not working properly or there is an ...

What could be the reason for the lack of responsiveness in my input box?

http://jsfiddle.net/4ws3L6kn/1/ Can anyone help me figure out why this isn't responsive? What mistake did I make? <div id="DIV_1"> <div id="DIV_2"> <div id="DIV_3"> <button id="BUTTON_4"> ...

Execute functions upon the completion of jQuery ajax requests

I need to trigger my function loadTest() once the bootstrap dialog is fully loaded and displayed. $(".btn").on("click", function() { $.ajax({ type: "POST", url: '/echo/html/', data: { html: '', ...