Revisit: Numbered headings with jQuery


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:

	$.fn.numberHeadings = function(){
			var values = new Array(0, 0, 0, 0, 0, 0);
			var context = $(this);
				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;

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: