1

I'm trying to get the ID of an element that is in a loop to trigger an event, but I can't get the ID nor content of the tag. I've done something similar on visual force pages, but I did it manipulating the DOM which I want to avoid in the lightning component ecosystem... any ideas?

I've tried event.getSource(), event.target, changing to a lightning:badge putting the span in it's own div but nothing seemes to work this is my component... I've seen this was a problem last year, but I post this anyway because I guess someone already solved this, without DOM manipulation.

<aura:component>
    <aura:attribute name="numberList" type="Object[]" access="private"/>
    <aura:iteration items="{!v.numberList}" var="obj">
        <span aura:id="{!obj.num}" class="{!obj.state}" onclick="{!c.numSelected}">
            {!obj.num}
        </span>
    </aura:iteration>
</aura:component>
2
  • Possible duplicate of component.find an aura:id item created in aura:iteration
    – sfdcfox
    Commented May 7, 2018 at 23:07
  • Nop, actually already tried, that, I'm avoiding the use of the ID tag, because, multiple instances of the component will coexist on the same page, and working with the ID caused me problems.
    – ekiim
    Commented May 7, 2018 at 23:12

2 Answers 2

4

When you're using normal HTML, you have a lot of flexibility in what you do with this. One solution not involving the use of id is to set a data attribute on the span:

<aura:component>
    <aura:attribute name="numberList" type="Object[]" access="private"/>
    <aura:iteration items="{!v.numberList}" var="obj">
        <span data-num="{!obj.num}" class="{!obj.state}" onclick="{!c.numSelected}">
            {!obj.num}
        </span>
    </aura:iteration>
</aura:component>

({ numSelected: function(component, event) {
     alert("You selected: " + event.target.dataset.num);
   }
})

Other variants of this technique are also possible.

2
  • Thanks! that worked with no haze! Thanks, What is the name of that? I've looked it up as data set, but get stuff that I don't really relate too that is not Lightning component right? that looks like htm5... for some reason, do you have documentation on it?
    – ekiim
    Commented May 7, 2018 at 23:29
  • @ekiim Yes, it's normal HTML5, and it works on IE11 plus all modern browsers. It's a pretty handy feature to know about.
    – sfdcfox
    Commented May 7, 2018 at 23:31
0

Thanks, all. Works really well for a button-like icon with text:

<span data-value="{!varContact.Id}" onclick="{!c.handleSelected}">
 <lightning:layout>
  <lightning:icon iconName="standard:contact" size="small"/>
  <div  title="{!varContact.name}">&nbsp;<a href="{!'/'+varContact.Id}">{!varContact.name}</a>
  </div>
 </lightning:layout>
</span>

And in the function:

var contId = event.target.dataset.value;

You must log in to answer this question.

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