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?
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);
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.