I am trying to access an input element on a event.target
object using event.target[0]
in TypeScript but I keep getting this error:
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'. Property '0' does not exist on type 'EventTarget'.
This is my code so far:
const counterDecrement = document.getElementById("counter__decrement")!;
const counterIncrement = document.getElementById("counter__increment")!;
const counterForm = document.getElementById("counter__form")!;
counterDecrement.addEventListener("click", () => {
counterValue.innerText = ( counterValue.innerText - 1).toString();
});
counterIncrement.addEventListener("click", () => {
counterValue.innerText = ( counterValue.innerText 1).toString();
});
counterForm.addEventListener("submit", event => {
event.preventDefault();
event.target as HTMLInputElement;
if (event.target) {
console.log(event.target[0]);
}
});
I get a squiggly red line under event.target[0]
(line 18)
Any ideas how to resolve this?
Thanks
CodePudding user response:
I think you can access it via counterForm's elements and you need to set what kind of html element is counterForm
you can simply use it in this way :
const counterForm = document.getElementById("counter__form") as HTMLFormElement;
counterForm.elements[0];