Created
February 28, 2011 06:06
-
-
Save Melipone/846996 to your computer and use it in GitHub Desktop.
Exercises from Chapter 12 of Eloquent Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ex. 12.1 | |
//Write a function asHTML which, when given a DOM node, | |
//produces a string representing the HTML text for that node | |
//and its children. You may ignore attributes, just show nodes | |
//as <nodename>. The escapeHTML function from chapter 10 is | |
//available to properly escape the content of text nodes. | |
function escapeHTML(text) { | |
var replacements = {"<": "<", ">": ">", | |
"&": "&", "\"": """}; | |
return text.replace(/[<>&"]/g, function(character) { | |
return replacements[character]; | |
}); | |
} | |
function isTextNode(node) { | |
return node.nodeType == 3; | |
} | |
function asHTML (node) { | |
document.write("<"+node.nodeName+"><br>"); | |
if (isTextNode(node)) | |
document.write(escapeHTML(node.nodeValue) + "<br>"); | |
for (var child in node.childNodes) | |
asHTML(child); | |
document.write("</"+node.nodeName+"><br>"); | |
} | |
// my solution does not work. I get an undefined. I don't know why. | |
// function asHTML(node) { | |
// 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 + ">"; | |
// } | |
// Okay, I peeked as the solution in the book and that works fine of course | |
// Ex. 12.2 | |
function removeElement (node) { | |
node.parentNode.removeChild(node); | |
} | |
// okay, I forgot to check whether it's the root node itself in which case, | |
// it wouldn't have a parent node. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment