Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,939 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);
}