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


Idan shami
Idan shami
13,251 Points

when should I use selectors and when should I need to traverse in the DOM?

I'm new to the DOM after I watched the basic tutorials I implemented the basics to my website, but all the time I felt committed to traverse the DOM and not to select EVERY element, but sometimes I felt that I need to select my elements one by one instead and it's not possible to access it by traversing.

so my question is: when do I need to select one by one and when do I need to traverse it? thanks a lot.

1 Answer

Steven Parker
Steven Parker
230,230 Points

The choice is usually based on your point of reference. If you have none to start with, a selector function would generally be needed. But in a delegated event handler, you might use traversal based on the event target. You could also still use a selector if you needed to access a specific element unrelated to the one generating the event.

When the choice isn't immediately clear, try thinking of how you implement it both ways, and what the results would be. If both are possible and produce the same results, one will likely yield more compact code.