I had a rather interesting use-case recently where I needed to take the contents of an HTML dropdown on a website which had timezones and then convert it into an object. But, I’ve been there before. How many times have you wanted a country dropdown or age dropdown and just wanted to copy one from an existing website?
I just opted for a simple for..loop in this case.
// Query the dom for all option elements inside of the select dropdown called timezone const options = document.querySelectorAll('#timezone option'); const obj = {}; for (const option of options) { obj.label = option.textContent.trim(); obj.value = option.value; }
I then use textContent
to get the label from the option, and then I call trim
to ensure that any whitespace doesn’t get copied over to my object. I call option.value
to get the value. But, here is the thing… If you’re taking this data with the intention of iterating over it later on, you probably want it to be an iterable type such as an array or even a map.
By creating an object and pushing it into an array, it will give us an array of objects, with our dropdown values dictated by a label
and value
property which correspond to our dropdown.
// Query the dom for all option elements inside of the select dropdown called timezone const options = document.querySelectorAll('#timezone option'); const values = []; for (const option of options) { values.push({ label: option.textContent.trim(), value: option.value }); }
If you’re not a fan of arrays, maybe you prefer maps instead, you can do pretty much the same thing. The first argument is the name and the second argument of the set
method is the value.
// Query the dom for all option elements inside of the select dropdown called timezone const options = document.querySelectorAll('#timezone option'); const values = new Map(); for (const option of options) { values.set(option.textContent.trim(), option.value); }
In this instance, I just opened up Developer Tools in Chrome and ran it directly in the console of the website that I wanted to call it on. If you console log the final values, you can then copy them from within Chrome. Right-click the printed value, choose, “Store as global variable” and it should create a new variable called temp1
if this is the first time running this code and then you can write copy(temp1)
to copy it to the clipboard.
Understandably, this is all pretty specific and non-typical Javascript, but if you ever want to copy a dropdown and convert it into an array, this will all do the trick.