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 DOM Scripting By Example Adding and Removing Names Registering Names

ywang04
ywang04
6,762 Points

document.querySelector('input'); VS form.querySelector('input');

Just a quick question:

In this video, Guil is using form.querySelector('input') instead of document.querySelector('input');

I just want to know the benefit of using this way. Thanks in advance.

const input = form.querySelector('input');

1 Answer

Steven Parker
Steven Parker
231,236 Points

Using querySelector('input') on the form element will return the first input element in that particular form, where using it on the document would return the first input element of the entire page.

Now it may be that the form's first input is the first one on the page, but being precise about coding could prevent problems if another form is placed at the top of the page at a later time.

ywang04
ywang04
6,762 Points

Thanks, Steven. It's clear to me.