0

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.