0

I'm creating and displaying lightning buttons in aura components dynamically. On click of each button, I'm trying to fetch its index using event.target.getAttribute. I'm able to get it but sporadically. Below is the code.

<div class="slds-grid slds-gutters product-btn">
  <aura:iteration items = "{!v.buttonList}" var  = "btn" indexVar = "index" >
    <div class="slds-col" data-row-index = "{!index}"> 
      <lightning:button  onclick="{!c.callJSController}" label="{!btn.key}"/>
    </div>
  </aura:iteration>
</div>

callJSController : function(cmp, event, helper) {
  let index = event.target.getAttribute("data-row-index"); //becomes null sometimes
}

Can anyone help me out what am I missing here or is there any other way to handle it efficiently.

1 Answer 1

0

You should use event.currentTarget instead of event.target to get the reference to the button element, then you could access to the parent div via parentElement. event.currentTarget always refers to the element to which the event handler has been attached, while event.target identifies the element on which the event occurred and which may be its descendant.

<aura:iteration items = "{!v.buttonList}" data-row-index="{!index}" var = "btn" indexVar = "index" >
    <div class="slds-col"> 
      <lightning:button onclick="{!c.callJSController}" label="{!btn.key}"/>
    </div>
</aura:iteration>

Moreover you don't need getAttribute: data-* attribute can be set and read by the camelCase name/key as an object property of the dataset:

callJSController : function(cmp, event, helper) {
  let index = event.currentTarget.parentElement.dataset.rowIndex;
}

Please note that index will be a string, not a number. If you need it as a number, you could use the unary + operator:

callJSController : function(cmp, event, helper) {
  let index = +event.currentTarget.parentElement.dataset.rowIndex;
}
2
  • When trying to keep data-row-index in lightning button, facing this error "The attribute "data-row-index" was not found on the COMPONENT markup://lightning:button" Feb 6 at 10:13
  • @sfdcdevsathy You're right, in aura we cannot set data attribute on standard component, I updated the answer.
    – RubenDG
    Feb 6 at 12:29

You must log in to answer this question.

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