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++) {
this.style.background = "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