Skip to content

Commit

Permalink
Add Element#replaceChildren()
Browse files Browse the repository at this point in the history
  • Loading branch information
lauriro committed Feb 6, 2023
1 parent 37372f7 commit fb2176d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
15 changes: 9 additions & 6 deletions index.js
Expand Up @@ -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() {
Expand Down Expand Up @@ -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
Expand All @@ -98,7 +95,7 @@ var boolAttrs = {
)
}
}
node.appendChild(frag)
replaceChildren.call(node, frag)

return html

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]
Expand Down
21 changes: 21 additions & 0 deletions test/index-spec.js
Expand Up @@ -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()

Expand Down

0 comments on commit fb2176d

Please sign in to comment.