Languages

JavaScript - Uncaught TypeError: this.previousSibling.focus is not a function

3 points
Asked by:
user4838
728

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>
1 answer
4 points
Answered by:
user4838
728

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 previousSibling to previousElementSibling:

// 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 span element 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]

 

See also

  1. JavaScript - focus HTML input field on label click

References

  1. Node.previousSibling - Web APIs | MDN
  2. Element.previousElementSibling - Web APIs | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join