How can assign multiple css classes to an html element through javascript without using any libraries?
+1
A:
guaranteed to work on new browsers. the old className way may not, since it's deprecated.
<element class="oneclass" />
element.setAttribute('class', element.getAttribute('class') + ' another');
alert(element.getAttribute('class')); // oneclass another
Tor Valamo
2010-01-01 12:55:30
+2
A:
Perhaps:
document.getElementById("myEle").className = "class1 class2";
Not tested, but should work.
tarnfeld
2010-01-01 12:55:45
+1
A:
Try this:
function addClass(element, value) {
if(!element.className) {
element.className = value;
} else {
newClassName = element.className;
newClassName+= " ";
newClassName+= value;
element.className = newClassName;
}
}
Similar logic could be used to make a removeClass function.
tybro0103
2010-01-02 07:21:26