Revisit: Numbered headings with jQuery

2012-02-11

This is a revisit to some old code i wrote that dynamically numbers headings in a text. You can read about the old code at Using JavaScript to number headings. This script uses the dynamic selectors of jQuery to ease the search for headings in a certain context. A bonus is that it works on several separate contexts simultaneously. Here is the code:

(function($){
	$.fn.numberHeadings = function(){
		this.each(function(){
			var values = new Array(0, 0, 0, 0, 0, 0);
			var context = $(this);
			context.find('h1,h2,h3,h4,h5,h6').each(function(){
				var level = parseInt(this.nodeName.replace(/h/i, ''));
				values[level - 1]++;

				//Create prefix
				var prefix = '';

				for(var l = 0; l < level; l++){
					prefix += values[l] + '.';
				}

				//Set prefix
				this.innerHTML = prefix + ' ' + this.innerHTML;
				for(var l = level; l < 6; l++){
					values[l] = 0;
				}
			});
		});
	}
})(jQuery);

You also need to include the jQuery framework in your document. Call the function when the document is completely loaded. Since this is jQuery, you start out with a selector on which you want to start the search for headings. Here is an example:

$(document).ready(function(){
	$('body').numberHeadings();
});