Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created July 11, 2017 15:38
Show Gist options
  • Save prof3ssorSt3v3/4d4173065a01814e3c82a9c178dbe46d to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/4d4173065a01814e3c82a9c178dbe46d to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Fragments</title>
<style type="text/css">
html{
font-size: 120%;
font-family: BlinkMacSystemFont, -apple-system, “Segoe UI”, Roboto, Helvetica, Arial, sans-serif;
line-height: 1.6;
}
li{ color: #666666; }
.bad{ color: #990000; }
.good{ color: #33CCFF; }
</style>
<script>
//document-fragments.js
//How to use documentFragment objects when dynamically
//creating new webpage content
let movies = ['Alien', 'Layer Cake', 'Star Wars', 'Star Trek', 'Jaws', 'Jurassic Park', 'Gross Pointe Blank', 'Eternal Sunshine of the Spotless Mind', 'Memento', 'Dog Soldiers', 'The Host', 'Gran Torino', 'Close Encounters of the Third Kind', 'Good Will Hunting', 'Casino Royale', 'Almost Famous'];
//use the Array movies and create a list of movies on the page
//inside of the <ul id="movies">
let movieList;
document.addEventListener('DOMContentLoaded', init);
function init(){
movieList = document.getElementById('movies');
//BAD APPROACH - add new content to DOM one at a time
// movies.forEach(function(movie){
// let li = document.createElement('li');
// li.textContent = movie;
// li.className = 'bad';
// movieList.appendChild(li);
// })
//GOOD APPROACH - use a documentFragment and update DOM once
let df = new DocumentFragment();
movies.forEach( movie => {
let li = document.createElement('li')
li.textContent = movie;
li.className = 'good';
df.appendChild(li);
})
movieList.appendChild(df);
}
</script>
</head>
<body>
<header>
<h1>DOM Manipulation with Document Fragments</h1>
</header>
<main>
<h2>A List of Movies</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae reiciendis dolores culpa, similique modi ex laboriosam, totam cupiditate, eos est vitae! Optio nihil molestias architecto consectetur similique repellat ullam asperiores!</p>
<ul id="movies">
<li>About Time</li>
<li>The Time Travellers Wife</li>
<li>A Wrinkle in Time</li>
<li>The Time Bandits</li>
</ul>
</main>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment