cssName
CSS2Properties members or cssText
provides a way to restyle one element, but what if you want do so for several elements it would be complex.
One way is to script className
. The className
member represents the class attribute.
Consider the below html. Let us see how to script the class using javascript.
<ul class="blue"> <li><a id="adidas" href="http://www.adidas.com">adidas</a></li> <li><a id="asics" href="http://www.asics.com">ASICS</a></li> <li><a id="brooks" href="http://www.brooksrunning.com">Brooks</a></li> <li><a id="newBalance" href="http://www.newbalance.com">New Balance</a></li> <li><a id="nike" href="http://www.nike.com">Nike</a></li> <li><a id="saucony" href="http://www.saucony.com">Saucony</a></li> </ul>
Let’s see how to change the className
member for the <ul> element from blue to red.
document.getElementsByTagName("ul")[0].className = "red";
An element can be a member of two or more classes. So we can write a common javascript function as below to replace the class names.
function swapClass(element, oldClass, newClass) { var re = new RegExp("\\b" + oldClass + "\\b", "g"); element.className = element.className.replace(re, newClass); }
Note that both oldClass and newClass are strings.
swapClass(document.getElementsByTagName("ul")[0], "blue", "red");