Posted in Code Snippets, Salesforce

Salesforce Lightning : Get attribute of the elements – Event Handling

To get the attributes of elements that has been targeted (which element has been clicked), we can use two ways:

  1. event.getSource()
  2. event.target and event.currentTarget

For Base Lightning Components (like lightning:button), we can use event.getSource():

<aura:component>
    <lightning:button name="myButton" onclick="{!c.handleClick}"/>
</aura:component>
({
    handleClick: function(cmp, event, helper) {
        var buttonName = event.getSource().get("v.name"); // return myButton
    }
})

For standard HTML elements (like div, li, table), we can use event.target or event.currentTarget

<div class="myClass" onclick="{!c.handleClick}" data-div="myCustomArea">
    This is a custom area!
</div>
({
    handleClick: function(cmp, event, helper) {
        var buttonName = event.target.dataset.div; // returns myCustomArea
    }
})

You can also use:

  1. event.target.value to get the value of the element
  2. event.target.getAttribute("custom-attribute") to get the custom attribute of the element

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s