Skip to content

Commit

Permalink
Handle doctype and cdata when writing innerHTML
Browse files Browse the repository at this point in the history
CDATA creates a new DocumentType node
but this is good enough.
  • Loading branch information
lauriro committed Jul 23, 2015
1 parent a5bbd84 commit acf367f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
20 changes: 11 additions & 9 deletions index.js
Expand Up @@ -128,23 +128,25 @@ Node.prototype = {
set innerHTML(html) {
var match, child
, node = this
, tagRe = /<!--(.*?)-->|<(\/?)([^ \/>]+)([^>]*)>|[^<]+/mg
, tagRe = /<!(--([\s\S]*?)--|\[[\s\S]*?\]|[\s\S]*?)>|<(\/?)([^ \/>]+)([^>]*)>|[^<]+/mg
, attrRe = /([^= ]+)\s*=\s*(?:("|')((?:\\?.)*?)\2|(\S+))/g

for (; node.firstChild;) node.removeChild(node.firstChild)
for (; node.firstChild; ) node.removeChild(node.firstChild)

for (; (match = tagRe.exec(html)); ) {
if (match[1]) {
node.appendChild(node.ownerDocument.createComment(htmlUnescape(match[1])))
} else if (match[2]) {
if (match[3]) {
node = node.parentNode
} else if (match[3]) {
child = node.ownerDocument.createElement(match[3])
if (match[4]) {
match[4].replace(attrRe, setAttr)
} else if (match[4]) {
child = node.ownerDocument.createElement(match[4])
if (match[5]) {
match[5].replace(attrRe, setAttr)
}
node.appendChild(child)
if (!voidElements[child.tagName]) node = child
} else if (match[2]) {
node.appendChild(node.ownerDocument.createComment(htmlUnescape(match[2])))
} else if (match[1]) {
node.appendChild(node.ownerDocument.createDocumentType(match[1]))
} else {
node.appendChild(node.ownerDocument.createTextNode(htmlUnescape(match[0])))
}
Expand Down
11 changes: 11 additions & 0 deletions tests/samp1.html
@@ -1,9 +1,20 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/"><head>
<title>1 + 2 = 3</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
/*<![CDATA[*/
body { background-image: url("marble.png?width=300&height=300") }
/*]]>*/
</style>
<link rel="stylesheet" type="text/css" href="styles/a.css?123">
<!--[if lt IE 8]><link rel="stylesheet" type="text/css" href="styles/ie.css?123"><![endif]-->
<script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript">
//<![CDATA[
document.write("<");
//]]>
</script>
<style type="text/css">.class{position:absolute;}</style></head>
<body onload="run('code');" class="reset page">
<ul class="gr">
Expand Down

0 comments on commit acf367f

Please sign in to comment.