Created
June 11, 2020 10:32
-
-
Save LeanSeverino1022/f51ce577b389d03596f974eb7911f98f to your computer and use it in GitHub Desktop.
Insert an element after or before another #DOM #cheatsheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//The following helper function insertAfter() lets you insert a new element after an existing one in the DOM tree: | |
function insertAfter(newNode, referenceNode) { | |
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); | |
} | |
// example | |
var newEl = document.createElement('div'); | |
newEl.innerHTML = '<p>Hello World!</p>'; | |
var ref = document.querySelector('div.before'); | |
insertAfter(newEl, ref); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function insertBefore(newNode, referenceNode) { | |
referenceNode.parentNode.insertBefore(newNode, referenceNode); | |
} | |
// example | |
var newEl = document.createElement('div'); | |
newEl.innerHTML = '<p>Hello World!</p>'; | |
var ref = document.querySelector('div.before'); | |
insertBefore(newEl, ref); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment