Changing the content of all <pre> tags using JavaScript

Bruno Pinho picture Bruno Pinho · Feb 25, 2013 · Viewed 9.7k times · Source

I want to know how I change all the pre tags inside a document...

I'm using this:

var preContent = document.getElementById('code').innerHTML;

but this only changes the content of 1 pre tag... the one with the ID 'code'.

If you can show me how i can change all the pre tags using JavaScript I appreciate

Here's all the code:

window.onload = function () {
    var preContent = document.getElementById('code').innerHTML;
    var codeLine = new Array();
    var newContent = '<table width="100%" border="1" ' 
        + 'cellpadding="0" cellspacing="0" >';

    codeLine = preContent.split('\n');
    for (var i = 0; i < codeLine.length; i++) {
        newContent = newContent + '<tr><td class="codeTab1" >' 
            + i.toString() + '</td><td class="codeTab2">' 
            + codeLine[i] + '</td></tr>';
    }
    newContent = newContent + '</table>';

    document.getElementById('code').innerHTML = newContent;
}

PS: This is to make a look like a normal compiler with numbers before the line PPS: Each pre tag will have a different content and I want the same script to change it (if possible).

Answer

James McLaughlin picture James McLaughlin · Feb 25, 2013

You can use getElementsByTagName:

var preElements = document.getElementsByTagName('pre');

for(var i = 0; i < preElements.length; ++ i)
{
    var element = preElements[i];

    /* modify element.innerHTML here */
}