Apex Lightning-Aura – How to Identify the Clicked Div Element

I have multiple div element in my lightning component which are clickable and from all of them I'm calling the same controller method. I want to know the div name which is clicked in my component. I know I can have multiple controller methods but I just wanted to have only one.
I tried event.getSource().getLocalId(); but its returning null.

Component:

<aura:component implements="flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes" access="global">
    <aura:attribute name="isFlowLaunched" type="boolean" default="false" />
    <aura:if isTrue="{!v.isFlowLaunched}">

        <aura:set attribute="else">
            <div class="slds-grid slds-gutters">
                <div aura:id="button1" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12" >
                    <span ><img src="{!$Resource.lion}"/></span>
                </div>
                <div aura:id="button2" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12">
                    <img src="{!$Resource.dear}"/>
                </div>
                <div aura:id="button3" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12">
                    <span><img src="{!$Resource.tiger}"/></span>
                </div>
                <div aura:id="button4" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12">
                    <span><img src="{!$Resource.tiger}"/></span>
                </div>
            </div>
        </aura:set>
    </aura:if>
</aura:component>

Controller:

({
    clickHandler : function(component, event, helper) {
        console.log("Clicked");
        var clickedBtn = event.target.getAttribute("aura:id");
        console.log(">>> Div Name... "+clickedBtn);
    }
})

Best Answer

You can you dataset attribute to get the current clicked div.

<div data-id="thisDiv" aura:id="thisDiv">Click Me!</div>


clickHandler : function(component, event, helper) { 
    var id = event.currentTarget.dataset.id; //it will return thisDiv
    var getTargetedButton = component.find(id); //it will return the source button
}
Related Topic