Toggle Class – The jQuery Way vs. The Native Way

I work with a team of developers located in the US, Canada and Bangalore. On behalf of the North American team, I send daily status emails detailing what each dev worked on, as well as their svn commit log, so the offshore devs and project leadership can stay synced.

For the past 2 or 3 weeks I’ve been including little quick tips on CSS and javascript. The team I’m on is composed of people with a variable level of skills and this is an attempt to affect those levels.

I thought I’d start posting some of these to archive ones I would have found helpful when I first started programming.

We use jQuery in our project and the majority of the devs (including myself) learned javascript via jQuery. Below is what it takes to toggle a class using jQuery vs. native javascript. As you can see, we’ve had it easy.

The jQuery Way

$( '.some-class' ).toggleClass( 'newClass' );

The Native Way (I’m sure there are better ways):

var i = 0,
    elements = document.getElementsByClassName('some-class'),
    len = elements.length,
    classToggle = function( element, tclass ) {

        var classes = elements[i].className,
            pattern = new RegExp( tclass );
            hasClass = pattern.test( classes );

        classes = hasClass ? classes.replace( pattern, '' ) : classes + ' ' + tclass;
        elements[i].className = classes.trim();

for ( ; i < len; i++ ) {
    classToggle( elements[i], 'newClass' );

The native example could be wrapped up a bit tighter to make it easily reusable. One of the reasons the jQuery example is so concise is that it relies on it's own methods for making collections and performing loops. The $ and toggleClass functions have quite a bit of code backing them up. If I were to add in all of the source code jQuery uses to preform these tasks, things would look a lot different.

But that's not the point. The thing that has enabled me to use jQuery as just one of the tools in my toolbox, instead of the only tool, is understanding the underlying functionality.

A couple of good references: the jQuery source (of course) and the MDC.