Quick question here, I encountered this problem today while practicing some JS. I wanted to create a basic prototype to loop through a "div" background-color array on click, but I realized that assigning the element property to a variable (instead of using the event target) impedes me to change the actual values.
This is the JS code:
let colors = ["blue", "yellow", "orange", "red"]
let n = 1;
document.querySelectorAll('div').forEach(occurence => {
occurence.addEventListener('click', (e) => {
let classes = e.target.className;
classes = colors[n];
n ;
console.log(classes);
if (n >= 4) {n = 0;}
});
});
So, changing the actual e.target.className works just fine, but trying to change the assigned "classes" variable does nothing. I feel like this may be a matter of specificity, or JS being unable to access the actual property values, or some akin beginner mistake.
CodePudding user response:
e.target.className
passes by value when you have let classes = e.target.className
, so classes
contains a copy of its data. Changing classes
just changes the copy, rather than what's stored in e.target.classname
.
CodePudding user response:
Actually, you are not changing the value of e.target.className
. What you do, is assigning the value of e.target.className
to the variable/let-binding classes
. To assign one of the color values to the className
property, the assignment has to be the other way around:
e.target.className = colors[n];