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.
Tony Brackins26,489 Points
getElementByID()...but no ID's.
On this tutorial, we'll be manipulating the DOM by ID (and Class I suppose). But what if you want to manipulate the DOM on a pre-existing page that has no ID's or Classes (or very few)?
Selecting specific elements in the DOM without having an id or class to go by is a little tricky and really only works for a static document that won't change. You would need to know what index that element is at in the document. For example, if you want to target the 2nd paragraph on a page, you can push the results
getElementsByTagName('p') into a variable and then target the 2nd paragraph by using index 1 in the HTMLCollection that was generated. Here is a codepen to reflect what I am talking about. http://codepen.io/anon/pen/qdmPvR
It can be especially tricky to target certain elements with dynamic code which is often why ids and classes are used. It makes a job more difficult than it needs to be to not use specially made attributes for elements. It's generally not a good idea to use targeting without ids or classes.
Jason AndersTreehouse Moderator 145,561 Points
I've got to agree with Marcus. Manipulating the DOM without using Classes or IDs is very tricky and often leads to a mess. If you're doing styling for a website that's already coded (HTML), I would add classes and IDs before (or as I am) styling the site. My rule... there is never too much specificity.