VCF

Unit 6 · JavaScript in the page

querySelector vs getElementById: the # rule

querySelector takes a CSS selector, so an id needs #: querySelector('#title'). getElementById already knows it wants an id, so write getElementById('title') with no #.

The mix-up

What people often think

“You select an element by its id name alone.”

What the tutor says

Selectors work like CSS: an id needs a #, so write '#title'. Plain 'title' looks for a <title> element instead.

How it works

Plain querySelector('title') is a valid selector too: it looks for a <title> element, which is why it finds the wrong thing rather than throwing an error.

Both only find elements that already exist; neither creates one. If nothing matches, you get null.

An example

What worksJavaScript
document.querySelector('#title');
document.getElementById('title');
document.querySelector('.price');  // first element with class price
Same element, two ways; selectors work like CSS.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “getElementById needs the # too.”

    getElementById already knows it is looking for an id. Write getElementById('title') with no #.

  • “querySelector makes a new element.”

    querySelector only finds. It hands back an element that is already on the page, using the same selectors as CSS.

Practise it with a tutor watching

Select and change

Find any element on a page with code and change its text and style.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.