JS: insert Adjacent Element
node.insertAdjacentElement(position, newNode)
-
Move a element and insert it adjacent to node's begin/end tags.
Return the element inserted, or
null
if failed.position is a string, and must be one of:
"beforebegin"
β Before the beginning tag. (as previous sibling.)"afterbegin"
β After the beginning tag. (as first child.)"beforeend"
β Before end tag . (as last child)."afterend"
β After the tag. (as next sibling.)
π‘ TIP: use this to attach element, more flexible than
appendChild
orinsertBefore
// create new node p containing hi const y = document.createElement("p"); y.textContent = "hi"; // a existing node const x = document.getElementsByTagName ("p")[0] ; // insert after x. insertAdjacentElement("afterend", y);