How do I migrate a

<div aura:id="foo"></div>

from Aura to LWC when I use Aura Id for finding?


I have found the LWC docs to offload some of this to the MDN docs, so bringing this one layer higher (in the actual LWC docs would be nice) would have made it easier for us.

In scenarios where there are two components of the same type on your template, the equivalent to aura:id is to use a data-id tag and select it like this:


| improve this answer | |

The equivalent of using aura:id and component.find() in LWC is to use a standard DOM query selector like this:

const element = this.template.querySelector('selector');

We do have a restrictions to that standard behavior: you cannot use the id attribute as a selector as these are autogenerated by the framework. You are free to use any tag name or CSS class to filter the element that you wish to retrieve.

See Documentation.

| improve this answer | |
  • 3
    Adding to this, if you want 1:1 equivalency, you can use this.template.querySelector('[data-id="userform"]'). This helps if there are multiple of the same component. – tsalb Feb 18 '19 at 18:28
  • Thats worth its own answer. – Robert Sösemann Feb 18 '19 at 22:05
  • Using a custom attribute will work but it has a performance impact. CSS attribute selectors don't perform that well so you may be better off by adding a class attribute (even if you don't use it for styling) and use it to discriminate the right component: this.template.querySelector('.unique-class-name') – POZ Feb 20 '19 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.