Posted By

noah on 07/20/07


Tagged

css toggle library DOM name conditional binary className utilities mattkruse hasclass


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

leitmotiv


toggle classnames on a DOM element (supports multiple classnames)


 / Published in: JavaScript
 

URL: http://github.com/textarcana/jquery_plugins

Example

Assuming some element like

 < span id="foo" class="bar homer marge"  ></span>

Then switch #foo back and forth between class names as follows. Note that doing so does not destroy the other classnames that are attached to #foo.

 toggleClassname($('#foo')[0], 'bar', 'baz');

If this is applied to an element that does not have the classname bar then that classname will be added.

There is also a jQuery version of toggle class name and replace classname.

  1. /**
  2.  * Toggle ClassName
  3.  * Works on els with multiple classnames
  4.  */
  5.  
  6. function toggleClassname (el, newClassname, defaultClassname) {
  7.  
  8. if (hasClass( el, defaultClassname)){
  9. var re = new RegExp("(^|\\s)" + defaultClassname + "(\\s|$)");
  10. el.className = el.className.replace(re, ' '+ newClassname +' ');
  11.  
  12. } else if (hasClass( el, newClassname)){
  13. var re = new RegExp("(^|\\s)" + newClassname + "(\\s|$)");
  14. el.className = el.className.replace(re, ' '+ defaultClassname +' ');
  15.  
  16. } else
  17. el.className += ' ' + newClassname;
  18.  
  19. }
  20.  
  21.  
  22. /**
  23.  * Has Class? (Matt Kruse)
  24.  * Kruse's hasClass, with slight modification
  25.  * Determine if an object or class string contains a given class.
  26.  * see http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/b68cac304ee6de78/e445c1df18698a3f?lnk=gst&q=hasclass&rnum=3
  27.  */
  28.  
  29. function hasClass (obj, className) {
  30.  
  31. if (typeof obj == 'undefined' || obj==null || !RegExp) {
  32. return false;
  33. }
  34.  
  35. var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
  36. if (typeof(obj)=="string") {
  37. return re.test(obj);
  38. }
  39. else if (typeof(obj)=="object" && obj.className) {
  40. return re.test(obj.className);
  41. }
  42. return false;
  43. };

Report this snippet  

You need to login to post a comment.