addClass, removeClass and hasClass without jQuery

Class manipulation methods in jQuery are really handy, but when you need just them and nothing else out of jQuery, then using entire library seems like a little bit mistake. Using own versions of addClass, removeClass and hasClass sounds like a better idea and for this reason I have wrote following article, where you’ll find an example implementation of these methods.

Original functions were taken form here [http://www.avoid.org/?p=78]. But since I don’t know regular expressions (and even more — I don’t like complicating easy things) and because original one wasn’t working correctly in some rare occasions, I rewrote them my own to following shape:

[code language=”javascript”]
document.hasClass = function(objectName, className)
{
return (objectName.className.indexOf(className) != -1);
}

document.addClass = function(objectName, className)
{
if(!document.hasClass(objectName, className)) objectName.className += (objectName.className ? ‘ ‘ : ”) + className;
}

document.removeClass = function(objectName, className)
{
if(document.hasClass(objectName, className)) objectName.className = objectName.className.replace(className, ”);
}
[/code]

You may also be interested in “getElementsByClassName without jQuery” article.

Leave a Reply