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 Interactive Web Pages with JavaScript Selecting Elements and Adding Events with JavaScript Perform: Selecting Elements

Bruno Dias
Bruno Dias
10,554 Points

Can I add an id for Add task button?

Can I add an id for Add task button instead of using the getElementsByName() ?

What if I decide to add another button that comes before the Add button? I would end up with a conflict on my code, is that right? Wouldn't be easier and safer to use the getElementById for the Add button instead?

cc: Andrew Chalkley

Let me know your thoughts.

Erik Schultz
Erik Schultz
16,090 Points

Ids are meant to be used once. You can't use duplicate ids on one page. I would just target classes since you can have duplicates on one page.

1 Answer

Steven Parker
Steven Parker
218,692 Points

If you have a control that you create a unique behavior for, it might indeed be a good place to assign an ID and then locate it in the code using getElementById.

But as Erik reminded us, ID's must be unique. So if the behavior is to be shared by multiple controls, identifying them with name or class is a better choice.