[SalesForce] Lightning Component: Iterate list of elements to change style

I have a series of divs in a list-style view on a sidebar and I want to change the style of one when it's clicked. I want the previously-clicked div to lose the class name that was giving it the highlighted style, and then add the class name to the newly clicked div.

In a component controller, are you able to loop over a list of elements from the view? I'm looking for something like a ".each()" jQuery function that I can use w/lightning JS controller out of the box if possible?

<aura:iteration items="{!v.relationships}" var="r">
  <div aura:id="{!r.Id}" class="slds-page-header data-row" role="banner" onclick="{!c.showDetail}" data-id="{!r.Id}" data-name="{!r.Name}">
    {!r.Name}
  </div>
</aura:iteration>

In my css, I have this:

.THIS .data-row:hover {
    background-color:#54698d;
    color:white;
    cursor:pointer;
}
.THIS .data-row .selectedRow{
    background-color:#54698d;
    color:white;
}

Essentially, when I click on one div, I want to:

// do some kind of loop here to remove the "selectedRow" class from all the divs
//component.find(someElements).each()... // like jQuery...
// $A.util.removeClass(thisElement,"selectedRow");
// then add the class to my selected div...
$A.util.addClass(myElement,"selectedRow");

Best Answer

Here is a sample code for the scenario

<aura:component>
<aura:attribute name="arrvals" type="integer[]" default="1,2,3,4,5"/>  

<div aura:id="main">
    <aura:iteration items="{!v.arrvals}" var="r">
      <div aura:id="{!r.Id}" class="slds-page-header data-row" role="banner" onclick="{!c.showDetail}" data-id="{!r}" data-name="{!r}">
        Hello List No {!r}
      </div>
    </aura:iteration>
</div>

The JS controller

({
showDetail: function(component, event, helper) {
    var arr = [];
    arr = component.find("main").getElement().childNodes;
    console.log(event.target);
    for(var cmp in component.find("main").getElement().childNodes) {
        $A.util.removeClass(arr[cmp], "selectedRow");
    }
    var targetElement = event.target;
    $A.util.addClass(targetElement,"selectedRow");
    }
 })

The CSS class

.THIS .data-row:hover {
 background-color:#54698d;
 color:white;
 cursor:pointer;
}
.THIS .data-row.selectedRow{
  background-color:#54698d;
  color:white;
 }

Demo

enter image description here

Related Topic