Published: 2014-12-20
Updated: 2015-04-04
Web: http://fritzthecat-blog.blogspot.com/2014/12/the-self-displaying-page.html
Sometimes I had the desire to display source code from the HTML page I was writing directly in that page. Especially in Blog articles, where I discuss a lot of code. I mean, when I write an "inpage" JavaScript, copy that code, enrich it with syntax-highlighting and put it right into the same web page, that copy won't change when the original code changes. The ubiquitous copy & paste problem, one of the biggest drawbacks in software production.
Displaying parts of a page directly in that page is possible only with JavaScript. The code I present here is written without the use of jQuery
, it is plain JavaScript. It won't work in InternetExplorer-8, which does not support textContent.
In the head
of this HTML document I wrote following imports of highlightjs:
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
This is like described on the web page.
Now here is an example of what I am talking about. I hope it works in any browser.
Following script does not exist as HTML in this page, it is in a script
tag (where it belongs to).
The HTML you see is created on the fly when you navigate to this page, done by just that JavaScript you see here:
What is happening here?
The function displayElement()
creates a new pre
element. A pre
element preserves newlines. The function then puts the text of the given parameter element
(f.i. JS text from a script
tag) into that pre
element, and adds it to the HTML document as child of the given target
element. Finally the given highlighter
function gets called, with the newly created element as parameter, this adds colors.
What remains to do is finding the parameters for this function. For that purpose I marked the JavaScript with an id = "myscript"
, and the destination element with id = "target"
. The predefined JS function document.getElementById()
finds these elements. The syntax-highlighter is a function that checks if highlightjs is available and calls it on the given HTML element when so. The setAttribute("class", language)
is a hint for highlightjs. Finally the function displayElement()
is called with these parameters.
If you want to try this out, here is an HTM skeleton to start with. Copy & paste the above script into to the empty script
tag, save it as file and call it in your web browser via
in case the file was saved to
file:///home/me/self-display.html
/home/me/self-display.html
. 1 | <!DOCTYPE html> |
Maybe you also want to try out how the whole HTML document looks inside itself. Then you can add this line to the JavaScript:
displayElement(document.documentElement, "html", target, highlighter);
Here is a link to my demo page. Have fun!
ɔ⃝ Fritz Ritzberger, 2014-12-20