0

I am new to Typescript and I have a dropdown whose values I need to iterate through. This is the code I am trying:

var sortBy = document.getElementById("SortbySel");

I want to iterate through the options but since this is an HTMLElement, I am unable to do so. What would be the best way to do this?

  • Why do you need to fetch dropdown items from html? Isn't it better to have it defined in ts class and passed to drop down as options? – K. Stefaniak Jun 12 '18 at 14:48
  • 1
    Look here for how to do it in javascript https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript If typescript is confused about the structure / available functions of an object you can hack through it with `(foo as any).secretFunction()`. Better to find the .d.ts files and fix the source of the problem, sometimes that's too much trouble for a small thing – IrkenInvader Jun 12 '18 at 14:52
  • To add the values to a custom styled dropdown control. I needed to iiterate through the select element and add them to the custom control – Anthony Fernandes Jun 12 '18 at 15:22

2 Answers2

1

One way would be to use the querySelectorAll function:

var options = document.querySelectorAll('#SortbySel option');
for(var i = 0; i < options.length; i++){
    console.log(options.item(i).value);
}
mpallansch
  • 1,174
  • 6
  • 16
0

Check out this stackblitz POC where I iterated over select HTML element

If you are using typescript it is always better to use specific classes like HTMLSelectElement & HTMLOptionElement instead of using conventional var declarations as it helps a lot in intellisense.

the code looks like this -

let selectElement: HTMLSelectElement = 
document.getElementById('select') as HTMLSelectElement;

for (let i = 0; i < selectElement.options.length; i++) {
  let option: HTMLOptionElement = selectElement.options[i];
  console.log(option);
}
planet_hunter
  • 3,866
  • 1
  • 26
  • 39