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 JavaScript and the DOM (Retiring) Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

getElement... or querySelector?

I cant find a rule that tells me when i can use getElement.... or querySelector?
Stuck for few weeks now.

1 Answer

Hi Jason!

Sometimes the Treehouse course instructions, and therefore the task test(s), will require one or the other (and is often very unforgiving if you use the wrong one, instead.

getElementById and querySelector('#elementId') can in many cases be used interchangably, hawever.

querySelector can be a little more useful, sometimes, though

With getElementById, you are limited to targeting ONLY and element with an id.

With querySelector, you can also target an element's descendants directly.

With getElementById, you'd have to target the element and then daisy-chain on additional DOM traversal properties and/or functions to target its descendants.

So with querySelector, you could do:

const myDivLink = document.querySelector('#myDiv1 a');

With getElementBy Id you'd have to do something like this (to achieve the same goal):

const myDivLink document.getElementById('myDiv1').firstChild;

(Assuming the first child of the div is the anchor tag you want to target, that is!?!)

I hope that helps.

Stay safe and happy coding!

Oh thank you, with your help and Jennifer Nordells too I'm hoping I get my head around this, I have also gone back into some css research with selectors to help understand more aswell.