If you are going library-free, you might need to roll your own function like this.
function addClass(id,new_class){
var i,n=0;
new_class=new_class.split(",");
for(i=0;i<new_class.length;i++){
if((" "+document.getElementById(id).className+" ").indexOf(" "+new_class[i]+" ")==-1){
document.getElementById(id).className+=" "+new_class[i];
n++;
}
}
return n;
}
Usage
<div id="changeme" class="big red"></div>
<button onclick="addClass('changeme', 'round')">Add a class</button>
Modern browsers have a ‘classList’ dom element attribute:
There also exists a fix for IE 8+, more info here: developer.mozilla.org/en/DOM/element.classList
Also it is bad practice to use JavaScript inline with html elements, the convention is to attach it via as event handler.
This could be a possible alternative:
I’m sorry there is a small typo in my code:
Also, this would be executed as such:
@Liam: Great code! Adjusted it slightly by adding a toggle function. This way I can add/remove classes. In my case to show/hide the sibling elements in a table.
This snippet assumes that a U+0020 space is used to separate class names. While that would probably work in most situations, it’s important to note that there’s more than just one space character in HTML.
@the guys that didn’t like it:
simply don’t use it. Nobody is forcing you to use it.
I think it is a great snippet. The “”+word+”” search is pure awesomeness, this totally prevents any kind of unexpected results.
I love this website, I really didn’t think they will put my snippet
They didn’t explain what the “return n;” was for.
it is just to know how many classes where successfully added. That option was handy for me (and if someone is not really going to use it, well simply delete that line)
Guys what if i want to remove these classes automatically when i add a Class on some other element ?