Created
December 4, 2012 04:38
-
-
Save nmaier/4200605 to your computer and use it in GitHub Desktop.
DOM construction vs. string concat
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
function generateHTML_ok(nodes) { | |
var result = document.createElement("div"); | |
for (var n = 0; n < nodes.length; ++n) { | |
var node = nodes[n]; | |
var h1 = document.createElement("h1"); | |
h1.textContent = node.localName; | |
result.appendChild(h1); | |
var list = document.createElement("ul"); | |
for (var a = 0; a < node.attributes.length; ++a) { | |
var attr = node.attributes[a]; | |
var li = document.createElement("li"); | |
li.textContent = attr.name + ' = "'; | |
var vspan = document.createElement("span"); | |
vspan.className = "attribute-value"; | |
vspan.textContent = attr.value; | |
li.appendChild(vspan); | |
li.appendChild(document.createTextNode('"')); | |
list.appendChild(li); | |
} | |
result.appendChild(list); | |
} | |
return result.innerHTML; | |
} | |
function generateHTML_bad(nodes) { | |
var result = ""; | |
for (var n = 0; n < nodes.length; ++n) { | |
var node = nodes[n]; | |
result += "<h1>" + node.localName + "</h1>"; | |
result += "<ul>"; | |
for (var a = 0; a < node.attributes.length; ++a) { | |
var attr = node.attributes[a]; | |
result += "<li>" + attr.name; | |
result += ' = "<span class="attribute-value">' + attr.value + '</span></li>"'; | |
} | |
result += "</ul>"; | |
} | |
return result; | |
} | |
var arghh = document.createElement("a"); | |
arghh.setAttribute("nasty", "<script>alert(document.cookie);</script>"); | |
console.log("ok", generateHTML_ok([arghh])); | |
console.log("bad", generateHTML_bad([arghh])); | |
// [05:36:47.985] ok <h1>a</h1><ul><li>nasty = "<span class="attribute-value"><script>alert(document.cookie);</script></span>"</li></ul> | |
// [05:36:47.985] bad <h1>a</h1><ul><li>nasty = "<span class="attribute-value"><script>alert(document.cookie);</script></span></li>"</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment