Code Snippet
addClass Function
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:
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)
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.