liveBook · Manning

insertBefore

As explained in Build a Frontend Web Framework (From Scratch)

A DOM Node method that inserts a new node immediately before a specified reference node in the same parent.

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

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Explains the two-argument operation, indexed insertion, and movement, stopping at practical mounting and patching cases.
Examples
Demonstrates inserting a paragraph between siblings and moving an existing child before a target sibling.
What you can do after
Apply it via the DOM API to insert or move nodes during mounting and child reconciliation.
How it connects
Connects insertBefore() with DOM nodes, childNodes, mounting, virtual DOM reconciliation, and node movement.

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.