Probably a silly question, but the basic way I learned how to change CSS of something on click is
var x = document.getElementById("id");
x.style.height = "auto";
or whatever.
But say I want divs of a certain class to change CSS attributes when clicked. But not all at the same time, only the one I just clicked. Adding separate ID’s and functions to each of them seems irrational.
Thank you!
2
Answers
In order to change the CSS of individual elements when clicked without assigning separate IDs and functions, event delegation can be used with JavaScript. This means you have one event listener attached on a parent element that takes care of clicks on its child elements.
Example:
The
document.querySelectorAll()
would perhaps be the most canonical way to achieve that. Simply select your elements by their class name and attach an event listener to each element.If you didn’t want to toggle a class and target only a single specific attribute you can do that too: