0

Suppose I have a select tag like below and I want to update its value through any attribute in javascript, then how can I achieve it because document.getElementById will not work in the lightning Web Components

<select id="demoSel" name="demoSel"> 
3
  • 5
    Does this answer your question? How do you define an element with an ID attribute using LWC? Commented Jul 1, 2021 at 8:33
  • @PrzemysławTamoń I could not set the value using the dataset property aswell. I wanted to set the value of the element in js side only. Also not on the particular event of the target but on the any event. Commented Jul 1, 2021 at 13:24
  • @PrzemysławTamoń I have to update the select tag in the connected call back which I was facing challenge. Commented Jul 2, 2021 at 5:24

2 Answers 2

2

In order to access element in LWC you need to use

this.template.querySelector();

You cannot use ID in the above as the the IDs are generated dynamically when the component is rendered. But you can use other selectors namely the class and data-* attributes. For example if you add the class = "selectclass" to your select element, you can access it using

this.template.querySelector(".selectclass");

LWC reference for the above is at

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_components_dom_work

3
  • can I use like this.template.querySelector(".selectclass").value = "somevalue" because I want to set the value through js side. Commented Jul 1, 2021 at 13:20
  • It should work or instead of value attribute, use selectedIndex attribute. I am not sure of the your usecase but instead of select, it might be better to use lightning-combobox component. Commented Jul 1, 2021 at 14:27
  • I have to update the select tag in the connected call back which I was facing challenge. Commented Jul 2, 2021 at 5:26
0

https://salesforce.stackexchange.com/questions/255907/lightning-web-components-select-option-prepopulate-value

the above link answered my question. To be specific I had to use conditional rendering inside the option tag just like this:

 <option if:false={getSelectedOption}> 

and use getSelectedOption as getter in which particular object of the array is returned which has to be selected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.