[SalesForce] Question about lightning icon and button

I'm trying to create a button in a lightning component, the purpose of this button is to delete a record (in a list of records).

So for now the easiest way to do that is like that :

<button class="slds-button" onclick="{!c.deleteContact}" data-data="{!contact.Id}">delete</button>

because in this kind of button I can put the attibute data that help me to get the id of the record in the javascript, so I can delete the record selected.

But I'd like to replace the word delete in the button with an icon like that :

<button class="slds-button" onclick="{!c.deleteContact}" data-data="{!contact.Id}">
    <lightning:icon iconName="utility:delete" size="small" class="icon" />

But then when I try to click the delete button I got an error :

[event.target.getAttribute is not a function]

But I only try to add an icon, for me the way the button works is not changed ?

Here is the javascript function in case there is something wrong in it, but that method work when there is no icon in the button (the record is corectly deleted) :

deleteContact : function (component, event, helper) { 
    var id = event.target.getAttribute("data-data") || event.target.parentNode.getAttribute("data-data")
    var action = component.get("c.deleteCon");
        "idContact": id
    action.setCallback(this, function(actionResult) {
        component.set("v.contacts", actionResult.getReturnValue());  

Best Answer

The problem is that by adding an icon in the button, the element that is the origin of the event is now the icon. The target property of the event is linked to the originator of the event.

To resolve this, you can use the event.currentTarget property instead of event.target. The currentTarget property will linked to the element attached to the event listener (i.e. your button).

Related Topic