3

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" />
</button>

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");
    action.setParams({
        "idContact": id
    });
    action.setCallback(this, function(actionResult) {
        component.set("v.contacts", actionResult.getReturnValue());  
        helper.getContacts(component);          
    });
    $A.enqueueAction(action);   
},

1 Answer 1

3

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).

2
  • Thank you it works ! So it means that if I had put the word 'delete' into a div or a span tag for example, I would have used event.currentTarget too ?
    – dou
    Mar 8, 2017 at 10:44
  • 1
    You're welcome ! Glad I could help. If you put an html element inside the button, yes you'll have to use the event.currentTarget property too. Mar 8, 2017 at 10:46

You must log in to answer this question.

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