Newer Version Available

This content describes an older version of this product. View Latest

Adding and Removing Styles

You can add or remove a CSS style to an element during runtime.

The following demo shows how to append and remove a CSS style from an element.

Component source

1swfobject.registerObject("clippy.codeblock-0", "9");<aura:component>
2    <div aura:id="changeIt">Change Me!</div><br />
3    <ui:button press="{!c.applyCSS}" label="Add Style" />
4    <ui:button press="{!c.removeCSS}" label="Remove Style" />
5    
6</aura:component>
7

CSS source

1swfobject.registerObject("clippy.codeblock-1", "9");.THIS.changeMe {
2    background-color:yellow;
3    width:200px;
4}
5

Client-side controller source

1swfobject.registerObject("clippy.codeblock-2", "9");{
2    applyCSS: function(cmp, event) {
3        var el = cmp.find('changeIt');
4        $A.util.addClass(el.getElement(), 'changeMe');
5    },
6    
7    removeCSS: function(cmp, event) {
8        var el = cmp.find('changeIt');
9        $A.util.removeClass(el.getElement(), 'changeMe');
10    }
11}
12

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

Toggling a Class

To toggle a class, use $A.util.toggleClass(element, 'class',condition);, which adds or removes the class if condition is true or false respectively. The element parameter can be an HTML element or a component. This example sets or remove the hideEl class by passing in the flag parameter.

1toggleSpinner: function (cmp, flag) {
2    var el = cmp.find("mySpinner").getElement();
3    $A.util.toggleClass(el, "hideEl", ! flag);
4}
To conditionally set a class for an array of elements, pass in the array to $A.util.toggleClass();.
1mapClasses: function(arr, cssClass, condition) {
2    for(var element in arr) {
3        $A.util.toggleClass(arr[element], cssClass, condition);
4    }
5}

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. In such cases, passing in the component cmp is recommended over passing in the HTML element. For more information, see Events Fired During the Rendering Lifecycle.

Note

Refer to the JavaScript API Reference for more utility functions for working with DOM elements.