Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'focus' does not exist on 'Element'?

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?

like image 517
matmik Avatar asked Jan 06 '20 15:01

matmik


People also ask

Does not exist on type element?

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.

What does focus() do?

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.

How do you set focus on input field?

As simple as document. getElementById('your_text_box_id'). focus(); .


2 Answers

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()
like image 107
geffting Avatar answered Oct 19 '22 04:10

geffting


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

like image 29
E. Boussardon Avatar answered Oct 19 '22 04:10

E. Boussardon