Skip to content

Why ID selector does not work in LWC

We often use an ID selector in our client-side javascript to access the elements and it works as expected. But, this is not the same in case of LWC.

What happens to the ID in LWC:-
When we give ID to an element, the ID may be transformed into globally unique values when the template is rendered, which means that a random key number is attached at the end of the ID and If we try to get the element by the initially specified ID, it will not show up because the initially specified ID won’t match the transformed ID.

For instance, in the below example, I have given an ID to the lightning-input and at the time of rendering the value of ID is altered and 97 (random key) is added at the end.

accessElements.html

<template>
    <div style="background-color: white;" class="slds-p-around_medium">
        <lightning-input id={idValue} value={textValue} type="text" label="Name" placeholder="Type here..."
            onchange={handleInput}>
        </lightning-input>

        <div style="font-size: large; font-weight: 300;" class="slds-p-top_xx-large">Value of the "id" changed on render from 'defualt' to : {idValue}</div>
        <div style="font-size: large; font-weight: 300;" class="slds-p-top_small">Value of the lightning-input : {textValue}</div>
    </div>
</template>
accessElements.js

import { LightningElement, track } from 'lwc';

export default class AccessElements extends LightningElement {
    @track idValue = 'default';
    @track textValue;

    connectedCallback() {
        setTimeout(() => {
            this.idValue = this.template.querySelector('lightning-input').id;
        }, 2000);
    }

    handleInput(event) {
        this.textValue = this.template.querySelector('lightning-input').value;
        this.idValue = this.template.querySelector('lightning-input').id;
    }
}

Thus, instead of ID selector, we can use any valid CSS selector (such as data-id, class or another attribute).

Happy Learning!

Published inCoding Mania

2 Comments

  1. Vishal Vishal

    How do we grab element in LWC if not by ID ?

    • Avi Rai Avi Rai

      We can use the “querySelector” or “querySelectorAll” to get the element(s). For example:
      Using tag – this.template.querySelector(‘div’);
      Using class name (say select) – this.template.querySelector(‘.select’);

Leave a Reply

Your email address will not be published. Required fields are marked *