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