Get Select Option by Value Using Javascript

I have selection menu:

<div class="selector">
<select>
<option value="valueA">Value A</option>
<option value="valueB">Value B</option>
<option value="valueC">Value C</option>
</select>
</div>

and I need Javascript (no jquery!) to get option by value and change it's text (innerHtml)

for example when I run the function I need to get option with the value "valueB" from class "selector" and change it's text to Value Whatever.

2 Answers

I'd suggest:

document.querySelector('div.selector option[value=valueB]').text = 'Value whatever';

Further, in answer to the questions raised in comments:

I need to get only the second <option> element with the same value as the other <option> and change text only to the second <option>

To get all <option> elements with value="valueB":

document.querySelectorAll('div.selector option[value=valueB]')[1].text = 'Value whatever';

The differences are that document.querySelector() returns only the first (if any) match to the supplied CSS selector, as a node (rather than a NodeList), so properties are available directly; document.querySelectorAll() returns all the elements, in a NodeList, that match the supplied selector; so we have to use the (zero-based) index ([1]) to retrieve a specific node, and get/set its properties.

5
document.querySelector('[value=valueB]').innerHtml="innerHtml"

for text document.querySelector('[value=valueB]').text="text"

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest