Reputation: 467
I have a class hardware
that, when clicked, I would like to change the background color upon hitting my run
function. However, my click sets them all to the same color at once.
How would I distinguish between each hardware
with their respective click event?
function run(){
var selector = document.getElementsByClassName('hardware');
for (var i = 0; i < selector.length; i++){
var index = selector[i];
selector[i].style.backgroundColor = "hotpink";
}
}
<section onclick="run()" class="hardware">some text, nth-child is one</section>
<section onclick="run()" class="hardware">some text, nth-child is two</section>
<section onclick="run()" class="hardware">some text, nth-child is three</section>
<section onclick="run()" class="hardware">some text, nth-child is four</section>
<section onclick="run()" class="hardware">some text, nth-child is five</section>
Upvotes: 1
Views: 63
Reputation: 47662
Another possibility:
function run(event){
event.target.style.backgroundColor = "hotpink";
}
Array.prototype.forEach.call(
document.getElementsByClassName("hardware"),
function (el){
el.onclick = run;
}
);
<section class="hardware">some text, nth-child is one</section>
<section class="hardware">some text, nth-child is two</section>
<section class="hardware">some text, nth-child is three</section>
<section class="hardware">some text, nth-child is four</section>
<section class="hardware">some text, nth-child is five</section>
Upvotes: 1
Reputation: 73241
Just pass the element to the function using run(this)
, then set the color only for that element:
function run(el){
el.style.backgroundColor = "hotpink";
}
<section onclick="run(this)" class="hardware">some text, nth-child is one</section>
<section onclick="run(this)" class="hardware">some text, nth-child is two</section>
<section onclick="run(this)" class="hardware">some text, nth-child is three</section>
<section onclick="run(this)" class="hardware">some text, nth-child is four</section>
<section onclick="run(this)" class="hardware">some text, nth-child is five</section>
Upvotes: 3
Reputation: 940
Try this:
function run(selector){
selector.style.backgroundColor = "hotpink";
}
<section onclick="run(this)" class="hardware">some text, nth-child is one</section>
Upvotes: 1