Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the content of all <pre> tags using JavaScript

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

like image 670
Bruno Pinho Avatar asked Feb 25 '13 12:02

Bruno Pinho


People also ask

How do you style a pre tag?

HTML <pre> Tag. The <pre> tag in HTML is used to define the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the <pre> element is displayed in a fixed-width font, but it can be changed using CSS.

What is pre tag in Javascript?

Definition and Usage. The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

How do you get text inside a pre tag?

Use . innerHTML if you want to get the markup inside the tag and use . textContent if you only need the text.


2 Answers

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 */
}
like image 79
James McLaughlin Avatar answered Sep 30 '22 07:09

James McLaughlin


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";
}
like image 34
Tarun Kumar Avatar answered Sep 30 '22 05:09

Tarun Kumar