[SalesForce] Find value of div inside aura iteration on icon click!

I am trying to find the value of a div which is inside aura iteration on icon click which is also inside the same aura iteration. Here in this code below I am trying to find the value of the aura:id=streeAddress on the click of the icon below.

<aura:iteration items="{! v.filteredMduInfo }" var="mdu">
    <div>
        <div>
            <div aura:id="streetAddress">{!
                mdu.address.Name+', '+mdu.address.sumchans__city__c+'
                '+mdu.address.sumchans__provinceCode__c+' '+mdu.address.sumchans__postalCode__c }</div>
        </div>
        <div>                    
            <lightning:icon iconName="utility:desktop" alternativeText="Television"
                            size="small" onclick="{! c.tvIconClick }"/>
        </div>
    </div>              
</aura:iteration> 

Controller JS:

tvIconClick : function(component, event, helper) {
    console.log(component.find("streetAddress").get());        
},

Best Answer

You cannot directly do this with the information you get in the event handler as is. Instead, you can use the index or record Id to find the value.

<aura:iteration items="{! v.filteredMduInfo }" var="mdu" indexVar="mduIndex">
    <div data-record-id="{!v.mdu.Id}" data-index="{!mduIndex}">
        <div>
            <div aura:id="streetAddress">{!
                mdu.address.Name+', '+mdu.address.sumchans__city__c+'
                '+mdu.address.sumchans__provinceCode__c+' '+mdu.address.sumchans__postalCode__c }</div>
        </div>
        <div>                    
            <lightning:icon iconName="utility:desktop" alternativeText="Television"
                            size="small" onclick="{! c.tvIconClick }"/>
        </div>
    </div>              
</aura:iteration>

tvIconClick : function(component, event, helper) {
  var filteredMdu = component.get("v.filteredMduInfo"),
      wrapper = event.target.closest("[data-record-id]"); // or [data-index]
  // option 1
  console.log(filteredMdu.find(mdu => mdu.Id === wrapper.dataset.recordId));
  // option 2
  console.log(filteredMdu[parseInt(wrapper.dataset.index)]);
},

Either way, these would be appropriate methods for finding the correct record to work with.

Related Topic