Last active
December 16, 2015 12:59
-
-
Save nickjacob/5438816 to your computer and use it in GitHub Desktop.
overview of different ways to append to the DOM
This file contains 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
// inefficient because you call append multiple times | |
// this causes a reflow on each call (https://developer.mozilla.org/en-US/docs/Notes_on_HTML_Reflow) | |
$('#my-el').append('<div>hi</div>').append('<div>two</div>').append('<div>three</div>'); | |
// you could just make 1 string of HTML | |
var to_append = '<div>hi</div><div>two</div><div>three</div>'; | |
$('#my-el').append(to_append); | |
// or you can use documentFragment; | |
// documentFragment is a container for DOM elements that, when you eventually attach it to the DOM, disappears so | |
// that it's children are added to its parent (example below) | |
var frag = document.createDocumentFragment(), | |
one = document.createElement('div'), | |
two = document.createElement('div'), | |
three = document.createElement('div'); | |
// you can work with the DOM elements here; set any properties, etc. | |
one.innerHTML = 'hi'; | |
two.innerHTML = 'two'; | |
three.innerHTML = 'three'; | |
// append the elements to the fragment | |
frag.appendChild(one); | |
frag.appendChild(two); | |
frag.appendChild(three); | |
// append the fragment to the target element | |
$('#my-el').append(frag); // "frag" disappears and one, two, and three are added to #my-el | |
// the advantage of the last approach is that you can manipulate the DOM elements before you | |
// add them to the DOM; for example, you could attach event listeners, set speciali properties, | |
// or dynamically change content before you actually show them in the document |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment