I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected.
Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).
Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.
I'd do it like this:
// first, build a reverse lookup
var optCount = mySelect.options.length;
var reverseLookup = {};
for (var i = 0; i < optCount; i++)
{
var option = mySelect.options[i];
if (!reverseLookup[option.value])
{
// use an array to account for multiple options with the same value
reverseLookup[option.value] = [];
}
// store a reference to the DOM element
reverseLookup[option.value].push(option);
}
// then, use it to find the option
var foundOptions = reverseLookup["Value that you are looking for"];
if (foundOptions && foundOptions.length)
{
alert(foundOptions[0].id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With