Search code examples
javascriptdebuggingouterhtml

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?


Solution

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