JavaScript Loop Through Select Options – Example

Sometimes we need to iterate through all the options of a DropDown list (and perform operations based on each one). Here is how to do it(for a dropdown with the id “dropdownlist”)

JavaScript:

var x= document.getElementById("dropdownlist");
for(i=0; i<x.options.length;i++){
console.log(x.options[i].value);
//Add operations here
}

JQuery:

$("#dropdownlist > option").each(function() {
console.log(this.text + ' ' + this.value);
//Add operations here
});