Changing the content of all <pre> tags using JavaScript

10,629

Solution 1

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 */
}

Solution 2

First problem in you code . No two elements in a document can have same id .

So you can change it easily with jquery . look at the code .

$('pre').html("what ever text you want to show ");

Or with javascript you can do like this :

var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
   x.innerHTML = "what ever text you want to show";
}
Share:
10,629
Bruno Pinho
Author by

Bruno Pinho

Updated on June 09, 2022

Comments

  • Bruno Pinho
    Bruno Pinho almost 2 years

    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).