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?
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 {
'<': '<',
'>': '>',
'&': '&',
'\n': '<br />'
}[x];
});
Before outputting it. You can apply this to many other characters, say for instance if you wanted to output whitespace literally.
Do two things (all of these, not just one):
HTML.replace(/&/g, '&').replace(/</g, '<')
is enough.<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, '&').replace(/</g, '<') + '</pre>';
The above code works, I tested it in IE and also in Firefox using FireBug. Note that outerHTML
is not supported in Firefox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With