Javascript onclick child - Stack Overflow

I'm trying to do a simple onclick to child elements (without jQuery):document.getElementById('

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

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";
    }
}

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

相关推荐

  • Javascript onclick child - Stack Overflow

    I'm trying to do a simple onclick to child elements (without jQuery):document.getElementById('

    13小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信