jQuery: enabling CSS counters in Internet Explorer

Internet Explorer 7 (and lower) doesn't support CSS counters. Fortunately, jQuery is here to help us. The first thing is to set a series of counters and then cycle through the children element of a target element incrementing those counters and adding them to the markup. Given a basic structure like this, with three nested lists:

<ul>
  <li>Item</li>
  <li>Item</li>
  <li>Item
    <ul>
   <li>Item</li>
   <li>Item</li>
   <li>Item
     <ul>
    <li>Item</li>
    <li>Item</li>
  </ul>
    </li>
 </ul>
   </li>
</ul>

We can write the following jQuery code:

(function($) {


  $.fn.counters = function() {
  
    var counter = 0;
 var counter2 = 0;
 var counter3 = 0;
  
    this.find('li').each(function() {
 
   counter += 1;
 
   var item = $(this);
   var html = item.html();
   
   item.html('<span>' + counter + '. ' + '</span>' + html);
   
   var ul = item.find('ul');
   
   ul.find('li').each(function() {
   
     counter2 += 1;
  
  var item2 = $(this);
  var html2 = item2.html();
  
  item2.html('<span>' + counter + '. ' + counter2 + ' ' + '</span>' + html2);
     
     var ul2 = item2.find('ul');
  
  
     ul2.find('li').each(function() {
  
  
    counter3 += 1;
    
    var item3 = $(this);
    var html3 = item3.html();
  
  
    item3.html('<span>' + counter + '. ' + counter2 + '. ' + counter3 + ' ' + '</span>' + html3);
  
  });
   
   
   });
   
  
   
  
 
 
 
 });
    
  
    return this;
  
  };



})(jQuery);

Finally, we can add our counters:

$(document).ready(function() {

$('ul:first').counters();

});

You can see the demo below.

Demo

Live demo

One thought on “jQuery: enabling CSS counters in Internet Explorer”

Leave a Reply

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