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 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,232 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
231,275 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.