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.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
First, create the template variables for dropdown using #teams . Use the event binding to listen for the change event and link with the onSelect method. The onSelect method receives the reference variable and takes the value of the dropdown element. Next, create the onSelected(value) method in the TypeScript file.
Definition and UsageThe value property sets or returns the value of the option (the value to be sent to the server when the form is submitted). Tip: If the value property is not specified for an option element, then the text content will be sent to the server when the container form is submitted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With