Skip to content

Dynamically create a click event based on an array and change format of the clicked element

I have 5 div tags each with its unique class name and two of them have the same class except the second one has an extra class (i.e. “.cls2” and “.cls2.a”). I have put these classes in an array and I am trying to create a click event where the clicked element containing the class from the array will do something.

Here’s my HTML code

<div class="cls1"></div>
<div class="cls2"></div>
<div class="cls3"></div>
<div class="cls4"></div>
<div class="cls2 a"></div>

Here’s the javascript:

var classList = [".cls1",".cls2",".cls3",".cls4",".cls2.a"];
var myColors = ["red","blue","pink","green","black"];
const myVar = document.querySelectorAll(classList);

for (const myVars of myVar) {
    myVars.addEventListener('click', function () {
        for (var x = 0; x < myVar.length; x++) {
   = "lightblue";
            myVar[x].style.background = "purple";
            myVar[x].innerHTML = myVar[x].classList;                

So what I am trying to do is change the element that was clicked on by changing its background color to a unique color and change all other elements to another color. In this case, the element that was clicked on will change to “lightblue” and all other elements to “purple”. This works fine except I am struggling to figure out how to change the color of the clicked element with colors defined in var myColors instead of “lightblue”.

I’d like to get this done in pure javascript without jquery



Use forEach instead, to iterate over the colors array, and select the <div> with the same index separately. Then the added listener can iterate over all divs, assigning the static color, while adding the color being iterated over to the selected div:

const classList = [".cls1", ".cls2", ".cls3", ".cls4", ".cls2.a"];
const colors = ["red", "blue", "pink", "green", "black"];
const divs = document.querySelectorAll(classList.join(','));

colors.forEach((color, i) => {
  const div = divs[i];
  div.addEventListener('click', function() {
    for (const div of divs) { = "purple";
    } = color;
<div class="cls1">a</div>
<div class="cls2">b</div>
<div class="cls3">c</div>
<div class="cls4">d</div>
<div class="cls2 a">e</div>