13

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 2

21

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.