Languages

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

3 points
Asked by:
user4838
698

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>
1 answer
3 points
Answered by:
user4838
698

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 to nextElementSibling:

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

 

See also

  1. JavaScript - focus HTML input field on label click

  2. HTML - focus input field on label click

References

  1. Node.nextSibling - Web APIs | MDN
  2. Element.nextElementSibling - 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