Get Select Option by Value Using Javascript
I Have Selection Menu: Value a Value B Value C and I Need Javascript (No Jquery!) to Get Option by Value and Change It's Text (Innerhtml) for Example When I...
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.
document.querySelector('[value=valueB]').innerHtml="innerHtml"
for text document.querySelector('[value=valueB]').text="text"