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 trialRyan Miles
Full Stack JavaScript Techdegree Student 3,261 Pointsselecting the button with getElementById works, but using querySelector is returning null.
When I assign the 'btn-main' to a variable using
const btnMain = document.getElementById('btn-main');
Everything works as expected. However using
const btnMain = document.querySelector('.btn-main');
returns null. How should I properly using querySelector to select the button?
2 Answers
Jason Larson
8,361 PointsYou are probably using querySelector correctly, but you have the wrong value. You have '.btn-main'
, which would be correct if you were selecting something with a class of 'btn-main'. Values in the querySelector method are like CSS definitions. Since you are trying to select an item with an ID of 'btn-main', you want to use:
const btnMain = document.querySelector('#btn-main');
Note that you don't have to make this distinction with getElementById
because you are already explicitly saying that you are going to be using the ID, so there's no need to make a special differentiation in the parameter.
Erik Biebinger
7,299 PointsI had this issue too, because I did not update my html correctly. I am not sure if Guil is mentioning the change of the button id into a class. If so, sorry, my mistake.