Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between insertAdjacentElement() and insertBefore()?

Tags:

javascript

dom

I'm trying to understand the error DOMException: Node.insertBefore: Child to insert before is not a child of this node which I've seen in both React and Angular projects over time and I started wondering: why does it even matter if an element A is "a child of" element B? Why choosing Node.insertBefore() over Element.insertAdjacentElement()?

The way I see it, both have browser support for ages and both work for SVG. But Node.insertBefore() seems to have an awkward API to me, because it requires to specify the parent.

Am I missing something?

like image 230
kraftwer1 Avatar asked Nov 01 '25 20:11

kraftwer1


1 Answers

insertBefore() requires you to provide the parent node, an existing child node, and the new node to be inserted; the new node is put before the child node. The child node has to be an immediate child of the parent node, otherwise you get that error.

insertAdjacentElement only requires you to provide an existing node and the new node. The new node is inserted at some place related to the existing node. There's no need to provide the parent node.

insertAdjacentElement() is newer than insertBefore(), but both have been around for some time.

like image 195
Barmar Avatar answered Nov 04 '25 11:11

Barmar