addClass function


/ Published in: JavaScript
Save to your folder(s)

Description: A function that add a class to an element if the element doesn't have anyone, if it already has one, add a new class name.
Arguments: The elemento to which you want to add the class and the name of the class you want to add.

From book Dom Scripting by Jeremy Keith.


Copy this code and paste it in your HTML
  1. function addClass(element,value) {
  2. if (!element.className) {
  3. element.className = value;
  4. } else {
  5. newClassName = element.className;
  6. newClassName+= " ";
  7. newClassName+= value;
  8. element.className = newClassName;
  9. }
  10. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.