Matt Coady
Matt Coady

Reputation: 3856

Javascript onclick child

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

Answers (2)

xdazz
xdazz

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

The WORKING DEMO.

Upvotes: 0

Gaurang Tandon
Gaurang Tandon

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

Demo

document.getElementById('someID').children returns a HTMLCollection, so you were adding a onclick to a HTMLCollection, which turns out to be wrong.

Upvotes: 5

Related Questions