Is there any fast way to get an <option> from a <select> by value, using JavaScript?


Yes, you can use the querySelector() method to get the option element based on its value attribute. Here’s an example:

<select id="mySelect">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
const selectElement = document.querySelector('#mySelect');
const optionElement = selectElement.querySelector(`option[value="2"]`);
console.log(optionElement.textContent); // Output: "Option 2"

In this example, we first use querySelector() to select the select element with an id of mySelect. We then use the querySelector() method again to get the option element with a value attribute of 2 by using a CSS attribute selector ([value=“2”]).

Finally, we log the text content of the option element to the console. Note that this approach will only return the first option element with the specified value attribute. If you need to get multiple option elements with the same value, you can use querySelectorAll() instead.