insertBefore() places a node immediately before a reference node in the same parent. It is useful when a renderer must insert a child at a specific index instead of merely appending it. section 8.1.1
A practical insertion helper handles three responsibilities:
- Append when the index is null, undefined, or beyond the current child count. section 8.1.1
- Reject negative indices because they do not identify valid child positions. section 8.1.1
- Use parentEl.insertBefore(el, parentEl.childNodes[index]) when the target index already exists. section 8.1.1
- Move an existing node by inserting it before the child currently occupying the desired position; the browser removes its original placement automatically. section 8.2.6
Insert a paragraph between two existing paragraphs
Create a div containing paragraphs with “One” and “Three”, create a new paragraph containing “Two”, and call insertBefore(newParagraph, existingSecondParagraph). The resulting order is One, Two, Three. section 8.1.1
Listing 8.1 The insert() function (mount-dom.js)
function insert(el, parentEl, index) {
// If index is null or undefined, simply append.
// Note the usage of == instead of ===.
if (index == null) {
parentEl.append(el) #1
return
}
if (index < 0) {
throw new Error(
`Index must be a positive integer, got ${index}`) #2
}
const children = parentEl.childNodes
if (index >= children.length) {
parentEl.append(el) #3
} else {
parentEl.insertBefore(el, children[index]) #4
}
}
A compact helper shows how null indices, invalid indices, append-at-end behavior, and insertBefore() combine into indexed DOM insertion. section 8.1.1
