Using JavaScript to number headings

2011-06-05

Today, I want to share a JavaScript with you all that I wrote yesterday. The script automatically numbers headings of a selected element. It looks like the numbered headings in Microsoft Word and automatically creates sublevels for smaller headings. The script searches a part of the document for child nodes of the type H1 to H6 but it is possible to set the starting level.

function heading_numbering(element, start_heading){
	var numbers = [0,0,0,0,0,0];

	//Iterate childNodes
	for(var i = 0; i < element.childNodes.length; i++){
		for(var heading = start_heading; heading <= 6; heading++){
			//Search childNodes for each heading
			if(element.childNodes[i].nodeName == "H" + heading){

				//Increase heading number
				numbers[heading - start_heading]++;
				number = numbers[0];

				//Generate heading number
				for(var n = 0; n < heading - start_heading; n++){
					number += "." + numbers[n + 1];
				}
				//Insert number before heading
				element.childNodes[i].innerHTML = number + " " + element.childNodes[i].innerHTML;

				//Reset subheading numbers for next heading
				for(var n = heading + 1; n <= 6; n++){
					if(heading != 6){
						numbers[n - start_heading]=0;
					}
				}
			}
		}
	}
}

Call the function when the document is completely loaded. You have to set an element in which you want to search and a starting level as arguments. Here is an example:

<body onload="heading_numbering(document.getElementById('content'), 1)">