JavaScript - Uncaught TypeError: this.nextSibling.focus is not a function
Hello, I've tried to focus an input
element when I click on the span element (with "Username:
" label) using this.nextSibling
property with focus()
method but I've got the following error:
Uncaught TypeError: this.nextSibling.focus is not a function
My code:
// ONLINE-RUNNER:browser;
<div>
<span onclick="this.nextSibling.focus()">Username:</span>
<input type="text"/>
</div>
It's because nextSibling
property returns the next Node which is Text node, not the next Element (HTMLInputElement in your's code case).
Quick solution:
Change the
nextSibling
tonextElementSibling
:
// ONLINE-RUNNER:browser;
<div>
<span onclick="this.nextElementSibling.focus()">Username:</span>
<input type="text"/>
</div>
Explaination
nextSibling
returns node, nextElementSibling
returns element. Each element is node, but node is element only in some cases, what whas shown in this article.
1. nextSibling
property
Returns the node immediately following the specified one in their parent's childNodes.
Note:
In the below example, the first node following the
span
element is the Text node containing a new line character (\n
).
// ONLINE-RUNNER:browser;
<div>
<span onclick="console.log(this.nextSibling);">Click here to see nextSibling:</span>
<input type="text"/>
</div>
Output:
[object Text]
2. nextElementSibling
property
Returns the element immediately following the specified one in its parent's children list.
// ONLINE-RUNNER:browser;
<div>
<span onclick="console.log(this.nextElementSibling);">Click here to see nextElementSibling:</span>
<input type="text"/>
</div>
Output:
[object HTMLInputElement]