EN
JavaScript - focus HTML input field on label click
3
points
In this article, we would like to show you how to focus input field on label click using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
<div>
<span onclick="this.nextElementSibling.focus()">Click the label to focus input</span>
<input type="text"/>
</div>
or:
// ONLINE-RUNNER:browser;
<div>
<input type="text"/>
<span onclick="this.previousElementSibling.focus()">Click the label to focus input</span>
</div>
Practical examples
By using JavaScript ,we are able to get input
element focus by calling its focus()
method.
It is good to consider 2 cases:
1. label before input
In this section, we use nextElementSibling
property that lets to get next element to the label.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>
<span onclick="this.nextElementSibling.focus()">Field name</span>
<input type="text"/>
</div>
</body>
</html>
2. label after input
In this section, we use previousElementSibling
property that lets to get previous element to the label.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>
<input type="text"/>
<span onclick="this.previousElementSibling.focus()">Field name</span>
</div>
</body>
</html>