Why we are using:
(document.getElementById("ipv") as HTMLInputElement).value;
instead of:
document.getElementById("ipv").value;
?
This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.
The Input Text Object in HTML DOM is used to represent the HTML <input> element with type=”text” attribute. The <input> element with type=”text” can be accessed by using getElementById() method.
To get the value of an input element in TypeScript: Select the input element. Type the input element as HTMLInputElement using a type assertion. Use the value property to get the element's value.
The function getElementById
returns object with type HTMLElement
.
From lib.dom.d.ts:
/**
* Returns a reference to the first object with the specified value of the ID or NAME attribute.
* @param elementId String that specifies the ID value. Case-insensitive.
*/
getElementById(elementId: string): HTMLElement | null;
HTMLElement
type is the base type for the other tag types of the DOM.
For example, the type HTMLInputElement
extends HTMLElement
and have the property value
that the type HTMLElement
doesn't have.
From lib.dom.d.ts:
interface HTMLInputElement extends HTMLElement {
...
/**
* Returns the value of the data at the cursor's current position.
*/
value: string;
...
Since HTMLInputElement
extends HTMLElement
, the next lines can compile:
const inputTag = document.getElementById('name-input') as HTMLInputElement;
const value = inputTag.value;
document.getElementById()
won't be able to return a specific element type since it doesn't know in advance what that element will be, so you need to cast the result as an HTMLInputElement after the fact so that the value
property of that class can be recognized.
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