jQuery and CSS classes

jQuery provides several methods for working with CSS classes. In this post I'm going to discuss with you some practical examples of these methods and some insights on their proper use. We'll see how jQuery makes life easier to us by allowing for the insertion, deleting and toggling of CSS classes.

CSS cascade and specificity

In our examples we'll work on a simple unordered list with three items. The first key concept to remember is CSS cascade and specificity: you should always make sure that the CSS class you're going to use has a greater specificity than the previous class or styles. Otherwise, the styles you're adding with your class won't work. For example, this will work:

#test li.first {
 padding: 0.3em;
 background: #ffc;
}

#test li.test1 {
 padding: 1em;
 background: orange;
}

In this case both classes have the same specificity, but the latter wins because it comes later in the source, despite of the identical CSS declarations expressed in each rule. Instead, this won't work:

#test li.first {
 padding: 0.3em;
 background: #ffc;
}

.test1 {
 padding: 1em;
 background: orange;
}

In this case, instead, the former class wins because it has a greater specificity than the latter. So always make sure that the CSS classes you're going to use have a proper specificity.

Testing if an element has a class

If you don't know the name of the class you're going to test, you can simply run this check:

if(element.attr('class')) {

  // do something

}

This will simply test if an element has any class attached to it. Instead, if you know already the name of the class, you can use the hasClass() method:

if(element.hasClass('test1')) {
  
  // do something

}

An example:

$('#test-class').click(function(e) {
    
      $('#test li').each(function() {
      
        var $li = $(this);
        
        if($li.attr('class')) {
        
          var marker = '<strong>CSS class: ';
          marker += $li.attr('class') + '</strong>';
          
          $(marker).appendTo($li);
        
        
        } else {
        
          var notice = '<strong>No CSS class</strong>';
          $(notice).appendTo($li);
        
        
        }
      
      
      });
    
      e.preventDefault();
});

Adding and removing classes

You can add and remove classes with the addClass() and removeClass() methods, respectively. Bear in mind that jQuery doesn't change the value of a class attribute using the DOM core methods setAttribute() and removeAttribute() due to backward compatibility with IE. It simply resets and modifies the string contained in the className property of each element. Both jQuery's methods accepts a single string value containing the name of a CSS class or a space-separated list of class names. Example:

$('#remove-class').click(function(e) {
    
      $('#test li').each(function() {
      
        var $li = $(this);
        
        $li.find('strong').remove();
        
        var note = '<strong>CSS class: none</strong>';
        
        if($li.attr('class')) {
        
          var cssClass = $li.attr('class');
          $li.removeClass(cssClass).append(note);
          
        }
        
      
      });
      
      e.preventDefault();
    
    });
    
    
    $('#add-class').click(function(e) {
    
      $('#test li').each(function() {
      
        var $li = $(this);
         $li.find('strong').remove();
        
        if($li.attr('class')) {
        
          var classID = $li.attr('class');
          
          $li.removeClass(classID);
        
        }
      

      
      });
      
      $('#test li').eq(0).addClass('test1').next().addClass('test2').next().addClass('test3');
    
      e.preventDefault();
});

Toggling classes

When jQuery toggles a CSS class, it simply does the following:

  • if an element has already a class on it, it removes this class first and then adds the new one
  • if an element has no classes on it, the result is the same as using addClass().

This is dome by using the toggleClass() method, which accepts as its parameter the name of the new class you want to use in the place of the old one. An example:

$('#toggle-class').click(function(e) {
    
      var cssClasses = ['test1', 'test2', 'test3'];
      var index = -1;
      
      $('#test li').each(function() {
      
        index += 1;
      
        var $li = $(this);
        $li.find('strong').remove();
        
        if($li.attr('class')) {
        
        
          var classValue = $li.attr('class');
        
          if(classValue != cssClasses[index]) {
          
            $li.toggleClass(cssClasses[index]);
          
          
          }
        
        }
        
      
      
      });
    
      e.preventDefault();
});

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.