views:

247

answers:

5

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
+2  A: 

This works:

myElement.className = 'foo bar baz';
moff
+2  A: 

Perhaps:

document.getElementById("myEle").className = "class1 class2";

Not tested, but should work.

tarnfeld
+2  A: 

Try doing this...

document.getElementById("MyElement").className += " MyClass";

Got this here...

Ryan
+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