swirdlerr
swirdlerr

Reputation: 45

adding event listener on collection

if I have a collection that has the same class, how can I add an onclick event listener without effecting each item with that class.

<div class = "overlay">etc. etc.</div>
<div class = "overlay">etc. etc.</div>
<div class = "overlay">etc. etc.</div>
<div class = "overlay">etc. etc.</div>

I'd want to run the following but only effect the one I click...not all of them with the classname 'overlay':

x = document.getElementsByClassName("overlay")
x.addEventListener("click", function() { this.addClassName("hide"); } );

Upvotes: 0

Views: 139

Answers (1)

Hanif
Hanif

Reputation: 3795

Try it:

x = document.getElementsByClassName("overlay");
for(var i = 0; i < x.length; i++){
    x[i].addEventListener("click", function() { this.classList.add("hide"); })
}

Upvotes: 1

Related Questions