Inserting Paragraph Numbering

One of the idiosyncrasies of the public sector is that paragraphs in documents such as press releases are numbered. Rather than code entire press releases in ordered lists when paragraph tags are a better choice semantically, I opted to use javascript to insert paragraph numbers.

Fellow blogger Divya Manian;
was kind enough to contribute a slice of javascript for this purpose, given that my own javascript skills are non-existent.

// contributed by Divya Manian (http://nimbupani.com/)

function insertParaNumbers () {
var paradiv = document.getElementById('media-body');
var paras = paradiv.getElementsByTagName('p');
j = paras.length;

for(var i = 0; i < j ; i++ )
{
lineno = i+1;
insertvalue = "<span class='lineno'>"+lineno+"</span>";
paras[i].innerHTML = insertvalue+paras[i].innerHTML;
}
}

window.onload = insertParaNumbers

Problem is, paragraphs within #media-body that fall under lists (ordered or unordered) do not need the insertion of paragraph numbers. How would you exclude these paragraphs from the loop?

I tried to use Prototype’s childElements to define paradiv as only children and not grandchildren of #media-body. Didn’t manage to get it to work.

About these ads

2 responses to “Inserting Paragraph Numbering

  1. Well.. this sort of scenario calls out for JQuery!! :).

    My prototype sucks badly.. but try this in your Firebug console on one of those pages


    var orig = $$("#media-body p");
    var exclude = $$("#media-body ol p");

    console.log(orig.length);

    for (var index = 0; index < exclude.length; ++index) {
    var item = exclude[index];
    orig = orig.without(item);
    }

    console.log(orig.length);

    If it works for you, remove the console.log and use the orig array in the rest of the code above.

    And, no I dont have a lot of free time on my hands!! I am just bugged with all the work I have :P.

  2. After a couple of minutes with Deepak over gTalk, he provides the solution, using prototype’s .without to remove paragraphs within lists from the array.

    Thanks so much Deepak and Divya!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s