1

I have a LWC button, and on page load I want to get the id of that element. How can I achieve this? I have tried the below code, but it's not working.

In HTML:

<lightning-button data-id="myButton" label="Click Me"></lightning-button>

In JS:

buttonIDs=[];

connectedCallback() {
    const buttonElement = this.template.querySelector('[data-id="myButton"]');
    if (buttonElement)  this.buttonIds.push(buttonElement.dataset.id);
     
}
1
  • I need the Id to fetch some details from metadata, for one of my requirements. I will pass the element Id to apex and fetch the required details. On page load I need the Id.
    – rmajumder
    Commented Apr 3 at 15:53

1 Answer 1

0

You need to ensure that the DOM is fully rendered before attempting to access the elements.

The connectedCallback lifecycle hook is called when the component is inserted into the DOM, but it does not guarantee that the child elements are rendered.

Instead, you can use the renderedCallback lifecycle hook, which is called after the component has finished the rendering phase.

HTML::

<lightning-button data-id="myButton" label="Click Me"></lightning-button>

JS::

buttonIDs = [];

renderedCallback() {  
    const buttonElement = this.template.querySelector('[data-id="myButton"]');
    var arrBtn = [];
    arrBtn.push(buttonElement.dataset.id);
    this.buttonIDs.push(...arrBtn);
    console.log("data :: "+this.buttonIDs); 
}

Output:: enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .