abrahamlinkedin abrahamlinkedin - 2 months ago 10
Javascript Question

click function for each class item

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>




Answer

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>