Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  20] [ 7]  / answers: 1 / hits: 21616  / 13 Years ago, thu, june 2, 2011, 12:00:00

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?


More From » debugging

 Answers
35

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.


[#91886] Wednesday, June 1, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;