Skip to content

Commit 3c217fe

Browse files
fixed: Use the new moveBefore method instead of overwriting the old insertBefore
1 parent e78208f commit 3c217fe

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

dom.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
import { dashToCamelCase } from './strings.js'
22

3-
// Rely on the new moveBefore method to move nodes if it's available https://developer.mozilla.org/en-US/docs/Web/API/Element/moveBefore
4-
const MOVE_BEFORE_METHOD =
5-
typeof Element !== 'undefined' && Element.prototype.moveBefore
6-
? 'moveBefore'
7-
: 'insertBefore'
8-
93
/**
104
* Get all the element attributes as object
115
* @param {HTMLElement} element - DOM node we want to parse
@@ -65,7 +59,22 @@ export const removeChild = (node) => node.remove()
6559
* @returns {undefined}
6660
*/
6761
export const insertBefore = (newNode, refNode) =>
68-
refNode?.parentNode?.[MOVE_BEFORE_METHOD](newNode, refNode)
62+
refNode?.parentNode?.insertBefore(newNode, refNode)
63+
64+
/**
65+
* Move a node into its new position. Use the moveBefore method if it's available
66+
* @param {HTMLElement} existingNode - node to move
67+
* @param {HTMLElement} refNode - ref child
68+
* @returns {undefined}
69+
*/
70+
export const moveBefore = ((hasMoveBefore) => (existingNode, refNode) =>
71+
hasMoveBefore
72+
? refNode?.parentNode?.moveBefore(existingNode, refNode)
73+
: insertBefore(existingNode, refNode))(
74+
// Rely on the new moveBefore method to move nodes if it's available https://developer.mozilla.org/en-US/docs/Web/API/Element/moveBefore
75+
// cache the value of the check into a boolean variable
76+
typeof Element !== 'undefined' && Element.prototype.moveBefore,
77+
)
6978

7079
/**
7180
* Replace a node

dom.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
cleanNode,
44
clearChildren,
55
insertBefore,
6+
moveBefore,
67
moveChildren,
78
removeChild,
89
replaceChild,
@@ -67,6 +68,17 @@ describe('DOM', function () {
6768
expect(source.innerHTML).to.be.equal('<div></div><p>hello</p>')
6869
})
6970

71+
it('moveBefore', () => {
72+
const source = document.createElement('div')
73+
source.innerHTML = '<p>hello</p>'
74+
const div = document.createElement('div')
75+
const p = source.querySelector('p')
76+
77+
moveBefore(div, p)
78+
79+
expect(source.innerHTML).to.be.equal('<div></div><p>hello</p>')
80+
})
81+
7082
it('replaceChild', () => {
7183
const source = document.createElement('div')
7284
source.innerHTML = '<p>hello</p>'

0 commit comments

Comments
 (0)