Scripting Classes

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.

snippet
function swapClass(element, oldClass, newClass) {
    var re = new RegExp("\\b" + oldClass + "\\b", "g");
    element.className = element.className.replace(re, newClass);
}
element - is an Element node that you want to change newClass - is the name of the class you want to replace oldClass with.

Note that both oldClass and newClass are strings.

swapClass(document.getElementsByTagName("ul")[0], "blue", "red");
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +