top of page

LWC querySelector usage

Updated: Jun 6, 2023

In LWC this.template.querySelector is used to select an element, Here element can be div, span, input or any tag inside lwc component.

In querySelector we use classname to uniquely identify a particular element and if there are more than one element we use querySelectorAll and run a loop on it.


But there is more to querySelector, we can uniquely identify based on data-id, data-name, if there are more than one element.


for example



Here there are 4 spans, where classes are same but data-recid are different. so we can uniquely identify a particular span in following way.




and if you are using a variable for recid, use in following way.



similarly we can use tag name instead of class name.



we can also search element just on the bases of data element, like this.



40,270 views2 comments

Comments

Couldn’t Load Comments
It looks like there was a technical problem. Try reconnecting or refreshing the page.
bottom of page