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

Tony Brackins
Tony Brackins
28,766 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)?

2 Answers

Hi Tony,

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.

Tony Brackins
Tony Brackins
28,766 Points

Thanks! This really helps. Why I was asking is because I'm working on a legacy system with limited classes. But creating a chrome extension to manipulate.

Thx again

Oh awesome! You're welcome, Tony. If you need any more help on it, come on back here and post about it or as a new question, and I'll help you as much as I can.

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,858 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.