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 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
221,585 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.