Skip to main content

Ivan Teoh

Something personal yet public

174-homework1.html

(Source)

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>JavaScript 101</title>
    <script type="text/javascript">
        function load()
        {

            function forEach(array, action) {
                var i;
                for (i = 0; i < array.length; i++) {
                    action(array[i]);
                }
            }

            function escapeHTML(text) {
                var replacements = [["&", "&amp;"], ["\"", "&quot;"],
                                   ["<", "&lt;"], [">", "&gt;"]];
                forEach(replacements, function(replace) {
                    while (text.indexOf(replace[0]) != -1) {
                        text = text.replace(replace[0], replace[1]);
                    }
                });
                return text;
            }

            function isTextNode(node) {
                return node.nodeType == 3;
            }

            function map(func, array) {
                var result = [];
                forEach(array, function (element) {
                    result.push(func(element));
                });
                return result;
            }
            var first = true;
            function asHTML(node) {
                if (first) {
                    node.innerHTML = node.innerHTML.replace(
                      /\B\s\B|[\n\r\t]/g,'');
                    first = false;
                }

                if (isTextNode(node))
                    return escapeHTML(node.nodeValue);
                else if (node.childNodes.length == 0)
                    return "<" + node.nodeName + "/>";
                else
                    return "<" + node.nodeName + ">" +
                        map(asHTML, node.childNodes).join("") +
                        "</" + node.nodeName + ">";
            }

            console.log(asHTML(document.body));

        }

    </script>
</head>
<body onload="load()">
    <h1>This is a header!</h1>
    <p id="excitingText">
        This is a paragraph! <em>Excitement</em>!
    </p>
    <p>
        This is also a paragraph, but it's not nearly as exciting as the
        last one.
    </p>
</body>
</html>