Look, ma: no jQuery! Creating footnotes with JavaScript and the DOM

Look, ma: no jQuery! Creating footnotes with JavaScript and the DOM

How to create footnotes with plain JavaScript and the DOM.

Continuing the series of the old memories of a bygone age when there was no jQuery, here's a simple task that our ancestors used to accomplish with plain JavaScript and the DOM: creating footnotes on text. All we have to do in our markup is to wrap words with classed span elements. Then it comes JavaScript.

We have two routines to run:

  1. Adding a link with a progressive anchor to each span element.
  2. Creating an ordered list and populating it with list items featuring a progressive ID (the target of the previously created anchors) and the words marked as notes.

Here's the code:

var FootNote = function() {
    var targets = document.getElementsByTagName('span');

    var addLinks = function() {

        for (var i = 0; i < targets.length; i++) {

            var span = targets[i];
            var $class = span.className;
            if ($class.indexOf('note') != -1) {

                var note = document.createElement('a');
                note.href = '#note-' + (i + 1);
                note.appendChild(document.createTextNode('(' + (i + 1) + ')'));
                span.appendChild(note);

            }

        }

    };

    var createNotes = function() {

        var a = document.getElementsByTagName('a');
        var list = document.createElement('ol');

        for (var j = 0; j < a.length; j++) {
            var link = a[j];
            var href = link.getAttribute('href');
            if (href.indexOf('#note') != -1) {

                var parent = link.parentNode;
                var text = parent.childNodes[0].nodeValue;
                var li = document.createElement('li');
                li.setAttribute('id', href.replace('#', ''));
                li.appendChild(document.createTextNode(text));
                list.appendChild(li);

            }

        }
        document.body.appendChild(list);

    };

    addLinks();
    createNotes();

};


FootNote();

As you can see, the actual implementation of our routines is pretty trivial. Always remember, though, that with jQuery we need much, much less code. You can see the demo below.

Demo

Live demo