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>
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.

  • 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 May 7 '18 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 May 7 '18 at 23:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.