Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property selectedIndex does not exists on type HTMLElement

Tags:

typescript

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.

Thanks

like image 453
jvcoach23 Avatar asked Aug 24 '16 15:08

jvcoach23


1 Answers

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.


Edit

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;
}
like image 94
Nitzan Tomer Avatar answered Sep 19 '22 17:09

Nitzan Tomer