jvcoach23 jvcoach23 -4 years ago 551
TypeScript Question

property selectedIndex does not exists on type HTMLElement

I'm trying to convert some js files to using typescript in asp.net webforms. The javascript works but it won't compile in ts because of the errors. Here is the code

var mDropDownID = arySecondTier[x];
var DropdownList = (document.getElementById("ctl00_ContentPlaceHolder1_lvCASec2_Detail_ctrl" + mDropDownID + "_ddlPoints"));
var SelectedIndex = DropdownList.selectedIndex;

the error happens on the selectedIndex line. From what i've read with typescript there is no selectedIndex on the HTMLElement, that i need to use a subtype of HTMLElement. If that is the case i'm having problems finding what the name of that subtype would be. If it's something else, well then i'd love to know what.

I've seen some who convert the DropDownList to , but my first thought is doesn't that go against the reason you want to use typescript.


Answer Source

You just need to let the compiler that the DropdownList is a select element:

var DropdownList = (document.getElementById("ctl00_ContentPlaceHolder1_lvCASec2_Detail_ctrl" + mDropDownID + "_ddlPoints")) as HTMLSelectElement;
 var SelectedIndex = DropdownList.selectedIndex; // no error

Also, you can do this:

`ctl00_ContentPlaceHolder1_lvCASec2_Detail_ctrl ${ mDropDownID } _ddlPoints`

Instead of the string concatenation.


You know which type of element you need to have based on the actual element in the dom.
If you get a reference to a script element then it needs to be a HTMLScriptElement, if it's a div then HTMLDivElement and so on.

MDN is a great source for information, but in this case I'd just check the lib.d.ts (should be available from your IDE as well) to see what this element have.
For example the HTMLScriptElement has:

interface HTMLScriptElement extends HTMLElement {
    async: boolean;
    charset: string;
    defer: boolean;
    event: string;
    htmlFor: string;
    src: string;
    text: string;
    type: string;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download