Vs code .value is not recognized by intellisense

Issue

I am very new to javascript, but as I was working I was trying to figure out a way to get the text a user would input into an html input text box, but for some reason vs code does not recognize the intellisense required to do this.

My HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" id="first-input">
    <button id="submit-button">Submit</button>
    <script src="main.js" type="text/javascript"></script>
</body>
</html>

HTML

The JavaScript:

let firstInput = document.getElementById('first-input');
let submitButton = document.getElementById('submit-button');

submitButton.onclick = function () {
    console.log(firstInput.value);
}

JavaScript

In order to get the data inside an input text element, the code for that is .value, however when i start typing ".val-" the only recommendation VS code has is for .nodeValue.

no .value option, only .nodeValue

This means, in order to get what I want, I am using a command that the intellisense for vs code doesn’t recognize. However, even though intellisense does not find it, the code still operates as intended.

code is functional

Is there something I need to install or do to get access to this information? I am concerned there are many other things it doesn’t recognize and will make learning this language more difficult. Thanks in advance

Solution

This is because getElementById() doesn’t necessarily return an element with a .value property. For example, it could return a <div> element.

In order for the intellisense to know that you will have a .value property, you have to indicate with a JSDoc comment that the variable firstInput is going to be an <input> element. Like this:

/**
 * @type HTMLInputElement
 */
let firstInput = document.getElementById('first-input');
/**
 * @type HTMLButtonElement
 */
let submitButton = document.getElementById('submit-button');

submitButton.onclick = function () {
  console.log(firstInput.value);
}

Not to confuse you, but VSCode uses TypeScript to power its intellisense, even for JavaScript code.

Answered By – Jake Boone

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.