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!
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
What is the purpose of # in argument: document.querySelector('#info')
In the video, document.querySelector('#info') is used. I've successfully used the .querySelector() method, correct vocab?, with element IDs that are not preceded by a #, so I have no idea what it's doing there!
What is the # doing in the .querySelector() method? Are there a class of symbols that "do stuff" like this #? What is the name of that class of symbols?
Caleb Kemp12,754 Points
In Jquery, the "#" lets the selector know that it should be using the giving value to look for an id. '#myId', would have the selector search for an element with the id 'myId'.
But, why didn't the code break when I removed it?
Well, there could be a couple of possible reasons.
The browser stores a cache of the page you are working on, if you first made the correct version, then changed it. If the browser was still using the cached version, it would still work even though you changed your code.
If instead of using
querySelector('#id')and just used
querySelector('id'), the selector will use the value to search for the first element with that tag name and not for an id. So, if you had an element with a tag the same name as your id (say 'input'), the code would still function even though it might not be behaving as you intended.
I completed the example in the workspace and using the inspect page feature of the browser, I found that changing
const field = document.querySelector('#info'); to
const field = document.querySelector('info'); gave me the error
Cannot read properties of null (reading 'value')
As mentioned previously, writing
const field = document.querySelector('input'); would work and cause no error because an element with the tag name "input" was able to be found.
Hope that helps
Basically, when you do html or css, you have ids and classes, and that specific selector searches for an element with a css class( that is indicated by the "#" as oppossed to css classes which are indicated by dots as in ".doc". I hope that it helps