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
pauloliva
7,889 PointsWhat's the difference between assigning an ID to an element rather than using getElementsByTagName?
I know that assigning an ID to an element is better, because we are targeting that very specific item in the DOM.
I saw a video (Perform: Selecting Elements - Andrew) in which he uses the getElementsByTagName method but by reading at the documentation, the method will return an array and then you can select the first item in the array and be done with it.
The problem occurs when we have a huge site with multiple buttons since it will take some time for the entire array to be created and it will also take a lot of space in memory.
My question is: Isn't better to just use ID's rather than getElementsByTagName? Well, at least just in the example that I mentioned above.
P.S: I see the power of using getElementsByTagName, but even if we use it with lists, we will be selecting all the list items in our page.
Thanks!
1 Answer
Vittorio Somaschini
33,371 PointsHello Paul.
Well you can select pretty much anything now with javascript or jQuery, but I think there is a huge difference in getting the element by tag or by id.
id is unique, so it gives you the opportunity to select THAT thing that you want and only that one.
On the other hand if you get elements by tag name you will be able to edit all the element with that particular tag, which is pretty powerful to.
Let's say you want to hide all list tags after clicking on a particular button? There you go, you select them in a second.
Vittorio
pauloliva
7,889 Pointspauloliva
7,889 PointsI'm looking more for a comparison when it comes down to performance. Since you are fetching all the elements with that specific tag, it will obviously take longer and I could have a performance impact on the site due to the script fetching such elements.
I guess it would be better just to assign an ID to a specific list that you want to hide based on the event rather than fetching all list items, mostly because of performance I guess.
What do you think?