Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we are using HTMLInputElement in typescript?

Why we are using:

(document.getElementById("ipv") as HTMLInputElement).value;

instead of:

document.getElementById("ipv").value;

?

like image 718
Muthukrishnan Kandasamy Avatar asked Sep 14 '18 06:09

Muthukrishnan Kandasamy


People also ask

Why do I get object HTMLInputElement?

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.

What is HTMLInputElement in angular?

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.

How do I get HTMLInputElement?

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.

How do you read input values in TypeScript?

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.


2 Answers

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;
like image 69
cooldave Avatar answered Oct 11 '22 01:10

cooldave


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.

like image 12
BoltClock Avatar answered Oct 11 '22 01:10

BoltClock