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.
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.
Share Improve this question edited Mar 17, 2014 at 7:12 Gaurang Tandon 6,81911 gold badges51 silver badges95 bronze badges asked Mar 17, 2014 at 7:08 Matt CoadyMatt Coady 3,8667 gold badges43 silver badges64 bronze badges2 Answers
Reset to default 5This 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";
}
}
Demo
document.getElementById('someID').children
returns a HTMLCollection
, so you were adding a onclick
to a HTMLCollection, which turns out to be wrong.
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";
}
});
The WORKING DEMO.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745421780a4626997.html
评论列表(0条)