Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) Responding to User Interaction Event Listening, Bubbling and Delegation

Riadh Hamidou
Riadh Hamidou
Full Stack JavaScript Techdegree Student 3,711 Points

Is this question in the quiz correct ?

Hi all,

I've been going through the JavaScript and the DOM part of the techdegree, and I came across this question in the quiz.

Quiz Question 2 of 5

Given the following code, what will happen when the button element is clicked?

const button = querySelector('button.cancel'); button.addEventListener('click', () => { console.log('I clicked the button'); });

is the variable button defined correctly ? there should be "document." before "querySelector", or it doesn't matter?

First I thought nothing or an error will happen, but the correct answer in the quiz is : 'I clicked the button will be logged to the console'

Can you select an element without document. like in this case ?

Thank you

3 Answers

28,524 Points

It is not.

You are correct to question it. It's a common typo to forget the document part of the querySelector method but it is mandatory, leaving it off will not work.

Here is a jsfiddle that shows off the code from the quiz, if you open that page and look at the console you'll see that you get a reference error, and the button does in fact not work. If you add document before querySelector then the button will work.

I'm going to guess that the author of the quiz simply forgot to include the document part, it's unlikely that it was omitted intentionally.

Loris Guerra
Loris Guerra
17,536 Points

I think you're right. "querySelector" is a method on the "document" object, so you need to call it like

document.querySelector( //some stuff )

Or maybe you can use it this way, but it's a waste of time:

const querySelector = document.querySelector.bind(document);
const button = querySelector( //some stuff )