Reputation: 3856
I'm trying to do a simple onclick to child elements (without jQuery):
document.getElementById('link').children.onclick = function(){
this.style.color="#ff0000";
}
I want it to change the color to red for each element clicked. I would assume this method would work but it won't.
Upvotes: 0
Views: 5196
Reputation: 160863
You have to use a loop, if you don't want to introduce new variables, you could do:
[].forEach.call(document.getElementById('link').children, function(e) {
e.onclick = function () {
this.style.color = "#ff0000";
}
});
Upvotes: 0
Reputation: 6753
This should work:
var childs = document.getElementById('link').children; //returns a HTMLCollection
for (var i = 0; i < childs.length; i++) { // iterate over it
childs[i].onclick = function () { // attach event listener individually
this.style.color = "#ff0000";
}
}
document.getElementById('someID').children
returns a HTMLCollection
, so you were adding a onclick
to a HTMLCollection, which turns out to be wrong.
Upvotes: 5