Skip to content

Instantly share code, notes, and snippets.

@akshaymohite
Created October 15, 2018 19:30
Show Gist options
  • Save akshaymohite/27ebc39a0f44402de0db4a1fc973d209 to your computer and use it in GitHub Desktop.
Save akshaymohite/27ebc39a0f44402de0db4a1fc973d209 to your computer and use it in GitHub Desktop.
jquery-addClass.js
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
classes = classesToArray( value );
if ( classes.length ) {
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment