Skip to content

Instantly share code, notes, and snippets.

@dusekdan
Last active May 11, 2017 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dusekdan/f1bd3469cf42ff41c932a6a08e35d2a3 to your computer and use it in GitHub Desktop.
Save dusekdan/f1bd3469cf42ff41c932a6a08e35d2a3 to your computer and use it in GitHub Desktop.
Update wrong function call (refactoring left over)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// DOM Node Type ELEMENT (=> we are only interested in elements, we dont want (attributes/CDATA/etc.))
var DOM_TYPE_ELEMENT = 1;
// TAG NAME of root element we want to use for DOM tree traversing
var ROOT_NODE_TAG_NAME = 'html';
// HTML HELPER TAGS
var HTML_SPACE_ENTITY = '&nbsp;';
var HTML_LINE_BREAK = '<br>\n';
/**
* Crafts DOM Tree output to be printed
* startNode specifies the starting point of DOM tree to be printed
* nestLevel should start from 0 and grow to the maximum nest level
* of the last element in DOM Tree.
*/
function prepareDOMTreeOutput(startNode, nestLevel)
{
// Recursion fixed point - node is not a node => return
if (startNode == false)
{
return;
}
// Generate node output [SPACE times CURRENT NESTED LEVEL]
var result = HTML_SPACE_ENTITY.repeat(3*nestLevel);
result += startNode.tagName;
result += HTML_LINE_BREAK;
// Loop through available nodes
for (var i = 0 ; i < startNode.childNodes.length ; ++i)
{
// Filter out DOM elements that are not of ELEMENT TYPE
if (startNode.childNodes[i].nodeType == DOM_TYPE_ELEMENT)
{
result += prepareDOMTreeOutput(startNode.childNodes[i], nestLevel+1);
}
// And just to see what happens in the process, log to debug what was skipped
else
{
console.log("[nestLevel:" + nestLevel + "|Iteration:" + i + "]");
console.log(startNode.childNodes[i]);
}
}
return result;
}
/**
* Replaces the page contents with data from parameter
*/
function printData(data)
{
document.write(data);
}
</script>
</head>
<!--
DOM TREE PRINTING IS INVOKED HERE
===============================================================================
IT IS IMPORTANT FOR IT TO BE CALLED FROM ONLOAD, SO THE PAGE IS ALREADY LOADED
IF THE FUNCTION IS CALLED FROM THE SCRIPT ABOVE, ONLY PAGE CONTENT UNTIL THE
<SCRIPT> ELEMENT WILL BE PRINTED OUT = REST WAS NOT LOADED IN TIME OF EXECUTION
===============================================================================
-->
<body onload="printData(prepareDOMTreeOutput(document.getElementsByTagName(ROOT_NODE_TAG_NAME)[0], 0));">
<h1>My First Heading</h1>
<p>My <a><b>first</b><em> paragraph</em></a>.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment