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:
- Attach a click event to all
.group
elements
- On click, retrieve the attribute value of the clicked element
- 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>