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.

To toggle the class, use $A.util.toggleClass(element, 'class');, which adds or removes the class depending on the presence of the class in the element. Refer to the JavaScript API Reference for more utility functions for working with DOM elements.