Setting an option to selected depending on option value

I want to mark an option as selected if it has a particular value. I have got as far as

const clcb = document.getElementById("cashbook");
clcb.getElementsByTagName("option")[2].selected = "selected";

which sets the 2nd option to selected, but what I want is to set the option whose value is 2 to selected.

clcb.querySelectorAll('option').forEach(o => {
  if (o.value === '2') {
    o.selected = 'selected'
1 Like

I was wondering if there’s a better way to do this using the filter/map/reduce methods.
The only trouble is what to do if no option is found, and that’s where map becomes useful.

    .filter((o) => o.value === "2")
    .map((o) => o.selected = "selected");

filter/map/reduce return things, there’s no need to handle returns here.

Is this still working?

Yes it is.