Categories
JavaScript Answers

How to set the focus to the first input element in an HTML form independent from the ID with JavaScript?

Spread the love

Sometimes, we want to set the focus to the first input element in an HTML form independent from the ID with JavaScript.

In this article, we’ll look at how to set the focus to the first input element in an HTML form independent from the ID with JavaScript.

How to set the focus to the first input element in an HTML form independent from the ID with JavaScript?

To set the focus to the first input element in an HTML form independent from the ID with JavaScript, we can use the document.forms property to get the form and the inputs inside the form.

For instance, we write

document.forms[0].elements[0].focus();

to get the first form with document.forms[0].

Then we use elements[0] to get the first element in the form.

Finally, we call focus on it to focus on the element.

Conclusion

To set the focus to the first input element in an HTML form independent from the ID with JavaScript, we can use the document.forms property to get the form and the inputs inside the form.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *