Skip to content

Commit

Permalink
Merge pull request #848 from btea/task/#846-after-add-element
Browse files Browse the repository at this point in the history
#846@patch: After add element correctly.
  • Loading branch information
capricorn86 committed Apr 11, 2023
2 parents ed686e3 + 8776349 commit f9a7a22
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/happy-dom/src/nodes/element/ElementUtility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ export default class ElementUtility {
parentElement.children.splice(index, 0, <IElement>newNode);
}
} else {
parentElement.children.length = 0;

for (const node of parentElement.childNodes) {
if (node === referenceNode) {
parentElement.children.push(<IElement>newNode);
Expand Down
39 changes: 39 additions & 0 deletions packages/happy-dom/test/nodes/element/Element.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1076,6 +1076,45 @@ describe('Element', () => {
expect(element.children[2] === span).toBe(true);
});

it('After should add child element correctly', () => {
document.body.innerHTML = `<div class="container"></div>\n`;
expect(document.body.children.length).toBe(1);
const container = document.querySelector('.container');

const div1 = document.createElement('div');
div1.classList.add('someClassName');
div1.innerHTML = 'div1';
container.after(div1);
expect(document.body.children.length).toBe(2);

const div2 = document.createElement('div');
div2.classList.add('someClassName');
div2.innerHTML = 'div2';
div1.after(div2);

expect(document.body.children.length).toBe(3);
expect(document.body.children[1] === div1).toBe(true);
expect(document.body.children[2] === div2).toBe(true);
expect(document.getElementsByClassName('someClassName').length).toBe(2);
});

it('Insert before comment node should be at the correct location.', () => {
const span1 = document.createElement('span');
const span2 = document.createElement('span');
const span3 = document.createElement('span');
const comment = document.createComment('test');

element.appendChild(span1);
element.appendChild(comment);
element.appendChild(span2);
element.insertBefore(span3, comment);

expect(element.children.length).toBe(3);
expect(element.children[0] === span1).toBe(true);
expect(element.children[1] === span3).toBe(true);
expect(element.children[2] === span2).toBe(true);
});

// See: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
it('Insert the children instead of the actual element before another reference Node if the type is DocumentFragment.', () => {
const child1 = document.createElement('span');
Expand Down

0 comments on commit f9a7a22

Please sign in to comment.