diff --git a/index.js b/index.js index aed6288..f558dca 100644 --- a/index.js +++ b/index.js @@ -45,9 +45,8 @@ var boolAttrs = { }, set textContent(text) { if (this.nodeType === 3 || this.nodeType === 8) return (this.data = text) - for (var node = this; node.firstChild; ) node.removeChild(node.firstChild) - node.appendChild(node.ownerDocument.createTextNode( - rawTextEscape[node.tagName] ? text.replace(rawTextEscape[node.tagName], "<\\") : text + replaceChildren.call(this, this.ownerDocument.createTextNode( + rawTextEscape[this.tagName] ? text.replace(rawTextEscape[this.tagName], "<\\") : text )) }, get firstChild() { @@ -75,8 +74,6 @@ var boolAttrs = { , frag = doc.createDocumentFragment() , tree = frag - for (; node.firstChild; ) node.removeChild(node.firstChild) - for (; (m = tagRe.exec(html)); ) { if (m[4]) { tree = tree.parentNode || tree @@ -98,7 +95,7 @@ var boolAttrs = { ) } } - node.appendChild(frag) + replaceChildren.call(node, frag) return html @@ -211,6 +208,7 @@ var boolAttrs = { get previousElementSibling() { return getSibling(this, -1, 1) }, + replaceChildren: replaceChildren, hasAttribute: function(name) { name = escAttr(name) return hasOwn.call(this, name === "style" ? "styleMap" : name) @@ -443,6 +441,11 @@ function extendNode(obj, extras) { obj.prototype.constructor = obj } +function replaceChildren() { + for (var arr = this.childNodes, i = 0, l = arr && arr.length; i < l; ) arr[i++].parentNode = null + for (i = arr.length = 0, l = arguments.length; i < l; ) this.insertBefore(arguments[i++]) +} + function getElement(childs, index, step, type) { if (childs && index > -1) for (; childs[index]; index += step) { if (childs[index].nodeType === type) return childs[index] diff --git a/test/index-spec.js b/test/index-spec.js index b85b161..1f34c78 100644 --- a/test/index-spec.js +++ b/test/index-spec.js @@ -346,6 +346,27 @@ describe("DOM lite", function() { assert.end() }) + it("has replaceChildren", function (assert) { + var el = document.createElement("el") + , a1 = document.createElement("a") + , a2 = document.createElement("b") + + assert.equal(el.childNodes, []) + + el.replaceChildren(a1) + assert.equal(el.childNodes, [a1]) + + el.replaceChildren(a2) + assert.equal(el.childNodes, [a2]) + + el.replaceChildren() + assert.equal(el.childNodes, []) + + el.replaceChildren(a1, a2) + assert.equal(el.childNodes, [a1, a2]) + assert.end() + }) + it("has documentFragment", function (assert) { var frag = document.createDocumentFragment()