krb
krb

Reputation: 16345

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

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.

Upvotes: 10

Views: 14925

Answers (4)

Marco Valeri
Marco Valeri

Reputation: 491

You can also follow that way:

    <pre>
      <code>
        &lt;h1&gt;Hello World&lt;/h1&gt;
      </code>
    </pre>

With the above example you have this output:

<h1>Hello World</h1>

Upvotes: 1

Adam McKenna
Adam McKenna

Reputation: 2445

You need to escape the HTML, like so:

You can use HTML entities that are escaped and printed without compiling.

&#60; // will print <
&#62; // will print >

Using these two, you can print any HTML elements.

&#60;div&#62; // will print <div>

To solve your specific problem, you will need to parse the HTML string and convert the chevrons to these entities.

Upvotes: 3

pel&#243;n
pel&#243;n

Reputation: 413

This:

    <pre>
      <&zwj;div>Hello<&zwj;/div>
    </pre>

Prints this:

<div>Hello</div>

Zero Width Joiner = &zwj;

Upvotes: 15

jevakallio
jevakallio

Reputation: 35970

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>

Upvotes: 18

Related Questions