Skip to content

Commit

Permalink
Add Element#replaceChild(), tests and a fix for insertBefore()
Browse files Browse the repository at this point in the history
  • Loading branch information
developit committed Jul 10, 2016
1 parent edb8160 commit 22a3f73
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/undom.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,18 @@ export default function undom() {
insertBefore(child, ref) {
child.remove();
let i = splice(this.childNodes, ref, child);
if (child.nodeType===1) {
while (i<this.childNodes.length && (ref = this.childNodes[i]).nodeType!==1) i++;
if (!ref) this.appendChild(child);
else if (~i && child.nodeType===1) {
while (i<this.childNodes.length && (ref = this.childNodes[i]).nodeType!==1 || ref===child) i++;
if (ref) splice(this.children, ref, child);
}
}
replaceChild(child, ref) {
if (ref.parentNode===this) {
this.insertBefore(child, ref);
ref.remove();
}
}
removeChild(child) {
splice(this.childNodes, child);
if (child.nodeType===1) splice(this.children, child);
Expand Down
21 changes: 21 additions & 0 deletions test/undom.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,27 @@ describe('undom', () => {
});
});

describe('#replaceChild()', () => {
it('should replace a child', () => {
let parent = document.createElement('div');
let child1 = document.createElement('child1');
let child2 = document.createElement('child2');
let child3 = document.createElement('child3');
let child4 = document.createElement('child4');
parent.appendChild(child1);
parent.appendChild(child2);
parent.appendChild(child3);

expect(parent).to.have.property('childNodes').eql([child1, child2, child3]);
expect(parent).to.have.property('children').eql([child1, child2, child3]);

parent.replaceChild(child4, child2);

expect(parent).to.have.property('childNodes').eql([child1, child4, child3]);
expect(parent).to.have.property('children').eql([child1, child4, child3]);
});
});

describe('#setAttribute()', () => {
it('should set a given named attribute', () => {
let el = document.createElement('div');
Expand Down

0 comments on commit 22a3f73

Please sign in to comment.