0

Hello!
I have a ts() JavaScript Intellisense problem in vscode. When I type following lines:

const input = document.querySelector("#input");
const button = document.querySelector("#button");
button.addEventListener("click", () => {
   console.log(input.value);
});

I get an error that states that Property "value" not found in type Element.

Please suggest me!

1 Answer 1

1

document.querySelector() will return an Element type by default, which does not have a value property. You need to tell TypeScript a more specific kind of element that you are expecting the query selector to return, as it cannot deduce this from the query string alone.

Given that you expect the query selector to return an HTML input element you would use const input = document.querySelector<HTMLInputElement>("#input"); to narrow down the return type of the query selector. A value property exists on this type so now you can use input.value.

More specifically document.querySelector is a generic function, generics are used when something, such as the return type of a function, can be of more than one type. You can read more about generics and its syntax in the TypeScript documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but I'm not using TypeScript. I'm getting this error in VSCode only but in browser, everything works fine
@SagarikaDas I'm having the same problem as you. Have you found a solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.