Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display HTML markup in browser without it being rendered

Starting to implement Javascript, I need to do troubleshooting and would like to output HTML to the screen without it being rendered. I can access the element (in IE) by

document.getElementById("test").outerHTML

I think, but I can't prove what I'm getting to be sure.

So what do I do to have document.write show the entire element including tags?

like image 997
Lance Roberts Avatar asked Jun 02 '11 22:06

Lance Roberts


2 Answers

Do you mean you want the literal, for example, <b>Hello</b> instead of Hello?

If so, just do a quick:

myHTML = myHTML.replace(/[<>&\n]/g, function(x) {
    return {
        '<': '&lt;',
        '>': '&gt;',
        '&': '&amp;',
       '\n': '<br />'
    }[x];
});

Before outputting it. You can apply this to many other characters, say for instance if you wanted to output whitespace literally.

like image 188
Ry- Avatar answered Oct 06 '22 01:10

Ry-


Do two things (all of these, not just one):

  1. Replace HTML markup with entities: HTML.replace(/&/g, '&amp;').replace(/</g, '&lt;') is enough.
  2. Wrap it in <pre></pre> tags so the whitespace is not eliminated and it is shown in a monospace font.

You can also alert(HTML). In IE on Windows (at least) you can press Ctrl-C and paste the text contents of the dialog box elsewhere to see it plainly.

Two serial replaces is faster than using a function as the second argument of replace(). Three serial replaces is also faster when the string is very long as one might expect from a full HTML document.

Also, using document.write is probably not the best way. If you have a div with id output you can access it this way:

document.getElementById('output').innerHTML = '<pre>' + document.body.innerHTML.replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</pre>';

The above code works, I tested it in IE and also in Firefox using FireBug. Note that outerHTML is not supported in Firefox.

like image 24
ErikE Avatar answered Oct 06 '22 02:10

ErikE