Design a site like this with WordPress.com
Get started

LWC Selectors/Identification of elements

From the documentation of LWC, it is clear that we can use only querySelector and querySelectorAll for getting/selecting element(s) and that we cannot use ID selectors because they are modified at runtime (when rendered).

Now consider the below code:

<div class="first-class">
	<lightning-input class="second-class" ></lightning-input>
	<lightning-input class="second-class" ></lightning-input>
	<lightning-input class="second-class" ></lightning-input>
</div>

How will you set the value of exactly 3rd input dynamically? (Remember you cannot use Id).

Below is the way you can do it.

let firstClass = this.template.querySelector(".first-class");
let secondClasses = firstClass.querySelectorAll(".second-class");
secondClasses[2].value = 'Some Value';

Well, above logic seems confusing or more than necessary code lines? Can we make it better? Yes of-course!

We can use some other attribute(s) to select an element we want. As a safe method we can add data- attributes.

<div class="first-class">
	<lightning-input data-my-id="in1" class="second-class"></lightning-input>
	<lightning-input data-my-id="in2" class="second-class"></lightning-input>
	<lightning-input data-my-id="in3" class="second-class"></lightning-input>
</div>

Now to select the third input and set the value, use below:

this.template.querySelector("lightning-input[data-my-id=in3]").value = "Some Value";

Advertisement

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: