Add And Remove Styles on Lightning Components

It is possible to add and remove styles on Lightning components or element during runtime.

To retrieve the class name on a component, use component.find(‘myCmpId’).get(‘v.class’), where myCmpId is the aura:id attribute value and the class is added dynamically. 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.

Consider this component – AddRemoveCSS.cmp

<aura:component >
  <div aura:id="changeBtn">Change My Style!</div><br />
  <lightning:button class ="btn" onclick="{!c.addCSS}" label="Add Style" />
    <lightning:button onclick="{!c.removeCSS}" label="Remove Style" />	
</aura:component>

I added the btn class to the Add Style button to style it a little bit. Check the style below in the STYLE code.

The controller:

({
	 addCSS: function(cmp, event) {
        var cmpTarget = cmp.find('changeBtn');
        $A.util.addClass(cmpTarget, 'changeStyle');
    },
    
    removeCSS: function(cmp, event) {
        var cmpTarget = cmp.find('changeBtn');
        $A.util.removeClass(cmpTarget, 'changeStyle');
    }
})

The STYLE code:

.THIS.changeStyle {
color: blue;
width: 150px;
margin-top: 20px;
margin-left: 15px;
}
.THIS.btn{
margin-right:10px;
margin-left: 15px;
}

The THIS.btn added both right and left margins to the first button to improve the user experience.

The result of clicking the Add Style button is attached below

Buttons to add and remove style

Reference

Lightning Aura Components Developer Guide