Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Created June 16, 2014 15:00
Show Gist options
  • Save martynchamberlin/ce3b0791a4fba7914dd3 to your computer and use it in GitHub Desktop.
Save martynchamberlin/ce3b0791a4fba7914dd3 to your computer and use it in GitHub Desktop.
Sometimes when content is coming out of a CMS it's faster to target an element by just adding a unique class via jQuery. This does that for you with any element(s) of your choosing. See sample function call at the bottom.
jQuery(document).ready(function( $ )
{
/**
* @param obj - array of strings. The element name to be targeted
*/
function addClasses( objArray )
{
for ( i = 0; i < objArray.length; i++ )
{
// Save CPU by storing this in local variable
var obj = objArray[i];
// Unique counter
var j = 0;
// Classname must not start with dot. Check if exists
// and remove if so
var className = obj;
if ( className.substr( 0, 1 ) == '.' )
{
className = className.substr( 1 );
}
// Now iterate through elements and add the class
$( obj ).each(function()
{
$( this ).addClass( className + '-' + j );
j++;
});
}
}
addClasses( [".form-table", "h3", "tr", ".desc"] );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment