1

Looking to identify which button was pressed through name or id as there are three buttons in my LWC that each trigger the same function.

I've used a standard html button so i could style it in a specific way (instead of lightning-button).

Button:

<button class="form-help-button" aria-describedby="help" id="BussNameButton" onclick={revealHelp}> 

Some of the documentation showed the standard event being used with standard html elements (ie. event.target.name etc.). So that is what I tried by I have not had success:

revealHelp(event) {
   let id = event.target.id;

   console.log(id)
}

It is firing but id is undefined each time. Can i retrieve the id or name of a standard html button in lwc?

In this Stack Exchange thread, most solutions involve passing an attribute in the element which is not allowed in LWC

5

id shouldn't be used, because it is used by the framework for rendering purposes. Instead, just use a data attribute to specify the name:

<button data-name="myButtonName" ... />

...

onClickHandler(event) {
    var buttonName = event.target.dataset.name;
    ...

...

Edit: I also created a quick playground that demonstrates this.

1
  • Wasnt planning on using Id, was just looking for syntax. I see its working in the fiddle but having issues in my component with data-attribute, seems to be causing an error. None the less, the currentTarget syntax does work. Thanks – Bobbygllh Feb 11 '20 at 20:32
-1

event.currentTarget.id or event.currentTarget.name is the correct syntax, i was just off on that part. Also use name not Id as it was coming across with appended numbers (many others mention this as well)

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.