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

When using querySelector(`h1`) , why is it that you write h1 as a string, and not just h1 ?

When using querySelector( h1 ) , why is it that you write h1 as a string, and not just h1 ?

  • so why this querySelector(h1) //querySelector Open parenthesis ( single quote ' h1 single quote ' ) Close parenthesis
  • instead of querySelector( h1 ) // whitout the single qoutes

is there a rule or reason behind writing it as a string, although it is not a string?

love to hear from you!

2 Answers

Steven Parker
Steven Parker
231,269 Points

Putting quotes around something defines it as a string literal, which is a string. The argument to querySelector will always be a string that contains a CSS-style selector. In this case, the string contents "h1" indicate that the element to search for is a heading type 1.

Leaving off the quotes would cause it to be taken as a variable name, which could still work if that variable had already been created and contained an appropriate string. For example:

let heading = document.querySelector('h1');

// the above will do the same thing as this:
let h1 = 'h1';
let heading = document.querySelector(h1);

// the variable name is not important, so this also would do the same thing:
let selector = 'h1';
let heading = document.querySelector(selector);
Richard Tillies
STAFF
Richard Tillies
Treehouse Teacher

Hi Max - the argument for querySelector() is a String, although most parsers are smart enough to interpret h1 (without quotes) as a String, similar to how you can normally omit quotes for most HTML tags in most cases.

Here's an example where you DO need quotes: querySelector('h2, h3') Without the quotes, this will not parse correctly and the output will likely be incorrect (if it processes at all).

Hope this helps!

oke, thanks!

Steven Parker
Steven Parker
231,269 Points

I was a bit shocked to read where you said "...although most parsers are smart enough to interpret h1 (without quotes) as a String,"

All JavaScript engines that I'm aware of would interpret h1 (without quotes) as a variable name, and not a string.