jQuery Enumerate

by tcloninger

HTML

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

CSS

ul{ margin-bottom:20px; }

JavaScript

// If you're sharing with others, you need to wrap your code
// in an IIFE (Immediately-Invoked Function Expression).
 
(function($){
    
    // A jQuery collection method that both "sets" and "gets."
     
    $.fn.enumerate = function( start ) {
      if ( typeof start !== "undefined" ) {
        // Since `start` value was provided, enumerate and return
        // the initial jQuery object to allow chaining.
         
        return this.each(function(i){
          $(this).prepend( "<b>" + ( i + start ) + "</b> " );
        });
         
      } else {
        // Since no `start` value was provided, function as a
        // getter, returing the appropriate value from the first
        // selected element.
         
        var val = this.eq( 0 ).children( "b" ).eq( 0 ).text();
        return Number( val );
      }
    };

})(jQuery);

$('li').enumerate(5).css('color','red');
alert( $('li').enumerate() );