Skip to content

Instantly share code, notes, and snippets.

@Scemist
Last active October 27, 2022 19:33
Show Gist options
  • Save Scemist/2dbd303e0e1ff71e7f5323590c53d61d to your computer and use it in GitHub Desktop.
Save Scemist/2dbd303e0e1ff71e7f5323590c53d61d to your computer and use it in GitHub Desktop.
Best JavasScript DOM functions

Add Element/HTML to Another Element

const container = document.querySelector('div')
const element = document.querySelector('p')

For node (element)

container.prepend(element)         // Insert at begin of container
container.replaceChildren(element) // Replace all inside container
container.replaceWith(element)     // Replace self container
container.append(element)          // Insert at end of container

For pure HTML

container.insertAdjacentHTML('afterbegin', '<p>Aloha moon.</p>') // Insert at begin of container
container.innerHTML = '<p>Aloha moon.</p>'                       // Replace all inside container
container.outerHTML = '<p>Aloha moon.</p>'                       // Replace self container
container.insertAdjacentHTML('beforeend', '<p>Aloha moon.</p>')  // Insert at end of container
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment