Scripting Classes


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="">adidas</a></li>
    <li><a id="asics" href="">ASICS</a></li>
    <li><a id="brooks" href="">Brooks</a></li>
    <li><a id="newBalance" href="">New Balance</a></li>
    <li><a id="nike" href="">Nike</a></li>
    <li><a id="saucony" href="">Saucony</a></li>

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);
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 #
Contents +