Creating a keyboard navigation, and facing the following issue:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
currentActive.previousElementSibling.focus();
}
The code works as expected, but TypeScript complains that Property 'focus' does not exist on 'Element'?
- the currentActive
is an <img />
tag.
I've tried assigning the currentActive to be a HTMLElement, by doing so:
let currentActive = document.activeElement as HTMLCollectionOf<HTMLElement>
, but it doesn't seem to like that.
What am I missing?
The error "Property 'X' does not exist on type 'Element'" occurs when we try to access a property that doesn't exist on an element of type Element . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.
focus() method sets focus on the specified element, if it can be focused. The focused element is the element that will receive keyboard and similar events by default.
As simple as document. getElementById('your_text_box_id'). focus(); .
I had the same problem and I solved it by defining the type of the element I was expecting from queryselector
. In my case I was expecting an input
element, so I did:
document.querySelector<HTMLInputElement>(`input[name=${element-name}]`)?.focus()
I would suggest trying something like this:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
(currentActive.previousElementSibling as HTMLElement)?.focus();
}
Note that optional chaining is available since TypeScript 3.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With