Phil Archer

Adding in Heading Numbers to HTML Automatically

This page provides a simple framework in which we can see the use of JavaScript to add numbers to all the headings automatically.


I should say straight away that I didn't write the script. All I've done is make trivial modifications to the script written by Liam Bennett which he wrote to originally to add heading numbers to Google Docs. In other words, I took out the reference to the iframe that Google Docs uses and put in the code to add the numbers automatically when the page loads.

This is Liam Bennett's work, not mine! His site, Clearly Secure, has a wealth of scripts that I can only recommend.


I came across this particular script when I was writing a new lecture for the W3C Mobile Web and Application Best Pratice Course. The best practice I had in mind was the one that says that it's better to reference your scripts at the end of your document, not the beginning. Now, adding in heading numbers may or may not be something you want to do, but the point is that by referencing the script at the end of the HTML, not the beginning, you optimise page rendering speed. Since the script simply adds in the heading numbers, it seemed like a conceptually simple example of something you can "add in" to a page after it's rendered. In that regard it's also consistent with the mantra of progressive enhancement since if you look at this page without JavaScript support — OK, you don't see heading numbers, but you still see the headings and it's all perfectly clear.

How Does Putting The Script At The End Help?

Browsers don't render HTML directly. They first create an internal model of the document known as the Document Object Model (DOM) and then render that. Scripting is how developers affect the DOM directly so when a browser begins to parse an HTML document, it stops the simple HTML → DOM → RENDER process when it gets to a script element as the script might alter the DOM. This is a gross simplification and there is significant variation between browsers but, to a first order approximation, the principle holds true.

By putting the script at the end of the document, just before the </body> tag, the page should be rendered in its "natural state" before the browser takes care of the script.

What's Going On Here?

This page has several headings and short bits of text. In theory at least, the script adds in the heading numbers after the page has first rendered.


I admit it would be hard to prove, especially as this is a very simple page, but the hope is that it is an easy to follow example.

Why Is This Page Here?

Because in the end I decided that I didn't need to use the example in the course after all but having found Liam Bennett's script and written an early version of this page, it seemed a shame to waste it altogether!

<script src="addNumbers.js"></script>