Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can assign multiple css classes to an html element through javascript without using any libraries?

share|improve this question
1  
I see by the answers there is some confusion here. Do you want to be able to apply a constant set of multiple classes to an element, or do you want to be able to add more classes to an element that it originally has? – ProfK Jan 1 '10 at 14:28

6 Answers

up vote 7 down vote accepted

Try doing this...

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

Got this here...

share|improve this answer

This works:

myElement.className = 'foo bar baz';
share|improve this answer

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
share|improve this answer

Perhaps:

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

Not tested, but should work.

share|improve this answer

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.

share|improve this answer

just use this

element.getAttributeNode("class").value += " antherClass";

take care about Space to avoid mix old class with new class

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.