Newer Version Available
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");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<aura:component>
18 <div aura:id="changeIt">Change Me!</div><br />
19 <ui:button press="{!c.applyCSS}" label="Add Style" />
20 <ui:button press="{!c.removeCSS}" label="Remove Style" />
21</aura:component>
22CSS source
1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17.THIS.changeMe {
18 background-color:yellow;
19 width:200px;
20}
21Client-side controller source
1swfobject.registerObject("clippy.codeblock-2", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17{
18 applyCSS: function(cmp, event) {
19 var el = cmp.find('changeIt');
20 $A.util.addClass(el.getElement(), 'changeMe');
21 },
22
23 removeCSS: function(cmp, event) {
24 var el = cmp.find('changeIt');
25 $A.util.removeClass(el.getElement(), 'changeMe');
26 }
27}
28The 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'), which adds or removes the class. The element parameter can be an HTML element or a component.
To hide or show markup dynamically, see Dynamically Showing or Hiding Markup.
To conditionally set a class for an array of elements, pass in the array to $A.util.toggleClass().1mapClasses: function(arr, cssClass) {
2 for(var element in arr) {
3 $A.util.toggleClass(arr[element], cssClass);
4 }
5}