Friday, 23 April 2010

Javascript: Add/Remove classes from elements

Here's a simple way of achiving this without any bloating libraries (I.e. JQuery etc.)
There is also a 'HasClass' method, which becomes quite useful.

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, ' ');
    }
}

No comments: