Creating a reusable JavaScript toggleClass function
<p>I have 'hasClass'</p>

<pre><code>function hasClass(elem, className) {
    return elem.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
</code></pre>

<p>Then the toggleClass function, it's very nearly working but I feel I am missing something really simple that's not letting it work. The problem is that the function correctly adds a class, but does not remove a class.</p>

<pre><code>function toggleClass(elem, className) {

    var newClass = ' ' + elem.className + ' ';

    if (hasClass(elem, className)) {
        elem.className = elem.className.replace(newClass, '');
    } else {
        elem.className += ' ' + className;
    }
}
</code></pre>

<p>Here's a JSFiddle for anyone who can help at all:
<a href="http://jsfiddle.net/P9zS9/" rel="nofollow">http://jsfiddle.net/P9zS9/</a></p>
