Snippets v2

Languages
My Snippets

Add a class name to an element Login or Register to Bookmark this snippet

Description Javascript

This function adds a class name to an element, keeping the existing classes but checking if it is already there first.

e is the element id as string or object reference.

t is the class as string.

Requires xGetElementById (available on this site).

The Code Download
  1. function addClassName(e,t) {
  2.     if (typeof e == "string") {
  3.         e = xGetElementById(e);
  4.     }
  5.     //code to change and replace strings
  6.     var ec = ' ' + e.className.replace(/^s*|s*$/g,'') + ' ';
  7.     var nc = ec;
  8.     t = t.replace(/^s*|s*$/g,'');
  9.     //check if not already there
  10.     if (ec.indexOf(' '+t+' ') == -1) {
  11.         //not found, add it
  12.         nc = ec + t;
  13.     }
  14.     //return the changed text!
  15.     e.className = nc.replace(/^s*|s*$/g,''); //trimmed whitespace
  16.     return true;
  17. }
Credits Contact JC

Added by JC on 12th November, 2007

Comments

There are no comments about this snippet.

Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment