Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

how i can access ?

hey i have more than button in my code i want to assign all the button different function how i can assign different functions to button?

1 Answer

Steven Parker
Steven Parker
232,192 Points

If you mean assign a different function to each button, it's just a matter of identifying each button somehow and replacing the onclick value with your function. For instance, if the button has an ID of (for example) "mybutton", you could do this:

document.getElementById("mybutton").onclick = MyFunction;

Or if the button had a unique class, such as "myclass" you could do this:

document.querySelector("button.myclass").onclick = MyFunction;

On the other hand, if you meant that you wanted to use the same function on all the buttons, that seems a bit odd but you certainly can.

You could do this to replace the function:

var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
    buttons[i].onclick = MyFunction;
}

Or you could do this to add another function:

var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", MyFunction);
}