my_htmlhighlighter.php
Quell Code
<style>
html {
background-color: #1D1F20;
}
code {
font-family: 'Monaco', monotype;
color: white;
font-size: 15px;
}
.tag {
color: #A7925A;
text-transform: lowercase;
}
.attribute-name {
color: #DDCA7B;
}
.attribute-value {
color: #95B289;
}
</style>
<code>
<article>
<h1>Display HTML as text</h1>
<p>This pen takes the content of the first <strong>code</strong> element, and by interpreting the DOM of the element it replaces the rendered elements with the raw HTML code. It also adds some style to it.</p>
</article>
<figure>
<svg width="300" height="300">
<circle cx="100" cy="100" r="20" fill="red"/>
<circle cx="150" cy="150" r="20" fill="lime"/>
<circle cx="200" cy="200" r="20" fill="blue"/>
</svg>
</figure>
<div data-sex="ficken">alle idioten wollen si cjen</div>
</code>
<script>
function isInline (node) {
return (
node.tagName === 'A' ||
node.tagName === 'SPAN' ||
node.tagName === 'STRONG' ||
node.tagName === 'SMALL' ||
node.tagName === 'CODE' ||
node.tagName === 'LABEL' ||
node.tagName === 'INPUT'||
node.tagName === 'FIGURE'
);
}
function convertAttributestoString(attrs) {
let string = '';
if(attrs.length === 0) {
return string;
}
for(let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
string += ` <span class="attribute-name">${attr.name}</span>`;
string += `=<span class="attribute-value">"${attr.value}"</span>`;
}
return string;
}
function convertHTMLtoString(node, level = 0) {
let string = '';
if(node.nodeType === document.ELEMENT_NODE) {
// If not inline then create a new block and add some padding
if(isInline(node) !== true) {
string += `<div style="padding-left: ${level*10}px">`;
}
// Self closing tag
if(node.childNodes.length === 0) {
string += '<span class="tag"><' + node.tagName + '</span>';
string += convertAttributestoString(node.attributes);
string += '<span class="tag">/></span>';
// Node with opening and closing tag
}else{
// Opening tag
string += '<span class="tag"><' + node.tagName + '</span>';
string += convertAttributestoString(node.attributes);
string += '<span class="tag">>' + '</span>';
// Content
for(let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
string += convertHTMLtoString(child, level+1);
}
// Closing tag
string += '<span class="tag"></' + node.tagName + '></span>';
}
// Padding close
if(isInline(node) !== true) {
string += "</div>";
}
}else if(node.nodeType === document.TEXT_NODE){
if(node.nodeValue.trim() !== '') {
string += node.nodeValue;
}
}
return string;
}
let root = document.getElementsByTagName('code')[0];
const string = convertHTMLtoString(root);
document.getElementsByTagName('code')[0].innerHTML = string; // Comment this line to see the original render
</script>