having fun with code

Very basic $ function to deal with element classes

If you are working with plain Javascript but still want to have some advantajes when dealing with element classes (element.className) you can write a small $ function like this:

  1. var $ = function(element) {
  2.    this.element = element;
  3.    this.getClasses = function() {
  4.      return this.element.className.replace(/\s+/,' ').split(' ');
  5.    }
  6.    this.hasClass = function(className) {
  7.      var classes = this.getClasses();
  8.      return (classes.indexOf(className) > -1);
  9.    }
  10.    this.addClass = function(className) {
  11.      if (!this.hasClass(className)) {
  12.        this.element.className += (this.element.className ? ' ' :'') + className;
  13.      }
  14.    }
  15.    this.removeClass = function(className) {
  16.      if (this.hasClass(className)) {
  17.        var classes = this.getClasses();
  18.        classes.splice(classes.indexOf(className), 1);
  19.        this.element.className = classes.join(' ');
  20.      }
  21.    }
  22.    return this;
  23. }

Then, once you have a variable that contains a DOM element, you can use it like this:

  1.   $(mydomelement).addClass('test');
  2.   if ($(mydomelement).hasClass('test')) alert('element has class test');
  3.   $(mydomelement).removeClass('test');
  4.   var classes = $(mydomelement).getClasses();

This will let you work with elements that have multiple classes very easily.

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation