/ Published in: JavaScript
URL: http://www.openjs.com/scripts/dom/class_manipulation.php
Expand |
Embed | Plain Text
function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!this.hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } } //call the functions addClass(document.getElementById("test"), "test"); removeClass(document.getElementById("test"), "test") if(hasClass(document.getElementById("test"), "test")){//do something};
Comments
Subscribe to comments
You need to login to post a comment.

I recommend adding this line to the end of
addClass()And changing this line of
removeClass()to this:
Doing so will remove all the extraneous spaces.
@Kerrick: You actually need to replace it with a space. If you are removing a class that falls between two other classes, replacing it with an empty string will join those other two classes.
Given:
elem.className = 'one two three';Replacing
\stwo\swith an empty string results in:elem.className = 'onethree';Instead, replace with a single space as shown in the original example, and then replace multiple spaces with a single space:
elem.className = elem.className.replace(reg,' ').replace(/\s+/g,' ');Then (in my example) you will be left with
elem.className = 'one three';.You may also want to add
.replace(/^\s|\s$/,'')to trim spaces from the very beginning or end of the.classNameproperty to take care of classes that were removed from the very beginning or end of the string.