Tag Archives: Adding and Removing Styles

Adding and Removing Styles on a Component During Runtime

You can add or remove a CSS style on a component or element during runtime. You can use the $A.util.addClass(cmpTarget, 'class') method to append CSS classes and $A.util.removeClass(cmpTarget, 'class') method to remove CSS classes from a component or element.

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

Here is an example to adding and removing Styles on a Component during runtime.


    <div aura:id="hwDiv">Hello World!</div><br />
    <lightning:button onclick="{!c.addCSS}" label="Add Style" />
    <lightning:button onclick="{!c.removeCSS}" label="Remove Style" />

JS Controller:

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

CSS Stylesheet:

.THIS.changeStyle {