Look, ma: no jQuery! Creating a page summary with JavaScript and the DOM

Look, ma: no jQuery! Creating a page summary with JavaScript and the DOM

An example of DOM manipulation with JavaScript without using jQuery.

Let's face the truth: jQuery is a great tool but has a major disadvantage: once you get accustomed to its methods and constructs, it's really hard to get back to the pure and plain JavaScript. In this article, I'd like to show you how to create a page summary with JavaScript and the DOM. This can be considered as a refresh to our memory. After all, jQuery is written in JavaScript.

We have the following HTML structure:

<body>
<h2>...</h2>
<p>...</p>
<!--more paragraphs-->
<h2>...</h2>
<p>...</p>
<!--more paragraphs-->
<h2>...</h2>
<p>...</p>
<!--more paragraphs-->
<!--structure continues-->
</body>

We want a summary to be displayed just before the first page heading. This summary must have a title and it should consists of an unordered list containing a series of page anchors with the related text (taken from each heading).

To accomplish this task, we first create a singleton object to encapsulate the logic behind our code:

var SummaryManager = {
	// methods here
	
	init: function() {
	
		// kicks things off
	
	}
};

SummaryManager.init();

Now each heading must have a unique ID. Let's create them:

idify: function() {

        var headings = document.getElementsByTagName('h2'),
            len = headings.length,
            i;

        for (i = 0; i < len; i++) {

            var heading = headings[i];
            heading.setAttribute('id', 'sec-' + (i + 1));


        }

}

IDs are in the form sec-1, sec-2 and so on. Done this, we can create our summary:

linkify: function() {

        var titles = document.getElementsByTagName('h2'),
            target = titles[0],
            list = document.createElement('ul'),
            size = titles.length,
            j, body = document.body,
            summary = document.createElement('h3');
        
        summary.appendChild(document.createTextNode('Summary'));

        for (j = 0; j < size; j++) {

            var title = titles[j];
            var anchor = title.getAttribute('id');
            var text = title.firstChild.nodeValue;
            var li = document.createElement('li');
            var a = document.createElement('a');
            a.setAttribute('href', '#' + anchor);
            a.appendChild(document.createTextNode(text));
            li.appendChild(a);
            list.appendChild(li);


        }

        body.insertBefore(list, target);
        body.insertBefore(summary, list);


}

We simply loop through all the headings and we collect their IDs and text nodes. Then we create all the list items together with their child links. You can see the demo below.

Demo

Live demo