Adding and Removing Styles

You can add or remove a CSS style on a component or element during runtime.

To retrieve the class name on a component, use component.find('myCmp').get('v.class'), where myCmp is the aura:id attribute value.

To append and remove CSS classes from a component or element, use the $A.util.addClass(cmpTarget, 'class') and $A.util.removeClass(cmpTarget, 'class') methods.

Component source

<aura:component>
    <div aura:id="changeIt">Change Me!</div><br />
    <lightning:button onclick="{!c.applyCSS}" label="Add Style" />
    <lightning:button onclick="{!c.removeCSS}" label="Remove Style" />
</aura:component>

CSS source

.THIS.changeMe {
    background-color:yellow;
    width:200px;
}

Client-side controller source

{
    applyCSS: function(cmp, event) {
        var cmpTarget = cmp.find('changeIt');
        $A.util.addClass(cmpTarget, 'changeMe');
    },
    
    removeCSS: function(cmp, event) {
        var cmpTarget = cmp.find('changeIt');
        $A.util.removeClass(cmpTarget, 'changeMe');
    }
}

The buttons in this demo are wired to controller actions that append or remove the CSS styles. To append a CSS style to a component, use $A.util.addClass(cmpTarget, 'class'). Similarly, remove the class by using $A.util.removeClass(cmpTarget, 'class') in your controller. cmp.find() locates the component using the local ID, denoted by aura:id="changeIt" in this demo.

Toggling a Class

To toggle a class, use $A.util.toggleClass(cmp, 'class'), which adds or removes the class.

The cmp parameter can be component or a DOM element.

Note

Note

We recommend using a component instead of a DOM element. If the utility function is not used inside afterRender() or rerender(), passing in cmp.getElement() might result in your class not being applied when the components are rerendered. For more information, see Events Fired During the Rendering Lifecycle.

To hide or show markup dynamically, see Dynamically Showing or Hiding Markup.

To conditionally set a class for an array of components, pass in the array to $A.util.toggleClass().
mapClasses: function(arr, cssClass) {
    for(var cmp in arr) {
        $A.util.toggleClass(arr[cmp], cssClass);
    }
}