Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a bit of HTML inside a <pre> tag?

Tags:

html

How do I put a bit of HTML inside a tag without escaping it? Or am I using an incorrect tag?

P.S. I cannot escape the HTML, it is produced by the server.

like image 784
Kristina Brooks Avatar asked Feb 20 '11 22:02

Kristina Brooks


People also ask

Can you put HTML inside script?

You can't do that. But you can use templates.

What is pre ></ pre tag in HTML?

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.

Can pre be inside P?

Since pre 's categories don't include "Phrasing content", pre cannot be put inside p .


1 Answers

If you have no control over the emitted HTML, you can still encode it on the client side.

Here is how you would escape all markup inside <pre> tags using the jQuery library:

$(function() {
    var pre = $('pre');
    pre.html(htmlEncode(pre.html()));
});

function htmlEncode(value){ 
  return $('<div/>').text(value).html(); 
} 

Edit: As requested, same code without using jQuery:

function encodePreElements() {
    var pre = document.getElementsByTagName('pre');
    for(var i = 0; i < pre.length; i++) {
        var encoded = htmlEncode(pre[i].innerHTML);
        pre[i].innerHTML = encoded;
    }
};

function htmlEncode(value) {
   var div = document.createElement('div');
   var text = document.createTextNode(value);
   div.appendChild(text);
   return div.innerHTML;
}

And run the encodePreElements after the DOM has been loaded:

<body onLoad='encodePreElements()'>
    <pre>Foo <b>bar</b></pre>
</body>
like image 192
jevakallio Avatar answered Oct 14 '22 08:10

jevakallio