Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created September 21, 2019 21:32
Show Gist options
  • Save prof3ssorSt3v3/837a34cc1dc898407809792cbcef2a53 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/837a34cc1dc898407809792cbcef2a53 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" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Injecting Strings into DOM as HTML</title>
<style>
p {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
font-size: 2rem;
line-height: 1.7;
color: #9933cc;
}
</style>
</head>
<body>
<header>
<h1>Injecting Strings into DOM as HTML</h1>
</header>
<main>
<!--
Injected HTML will go here
-->
</main>
<script>
let main = document.querySelector("main");
let strHTML1 = '<p>1. This is the <a href="#">String</a> with HTML.</p>';
let strHTML2 = '<p>2. This is the <a href="#">String</a> with HTML.</p>';
let strHTML3 = '<p>3. This is the <a href="#">String</a> with HTML.</p>';
let strHTML4 = '<p>4. This is the <a href="#">String</a> with HTML.</p>';
let strHTML5 = '<p>5. This is the <a href="#">String</a> with HTML.</p>';
let strHTML6 = '<p>6. This is the <a href="#">String</a> with HTML.</p>';
//version 1 - innerHTML
main.innerHTML = strHTML1;
//version 2a - document.createDocumentFragment()
//version 2b - new DocumentFragment()
let frag = new DocumentFragment();
frag.append(strHTML2); //will keep it as the same string
// innerHTML not available on a document fragment
// need to create actual DOM nodes to append...
// so we can do pattern matching on the string can create the nodes
// or use the DOMParser below to convert and then append
//console.log(frag);
//GREAT INSIDE A LOOP. DO THE APPEND AFTER THE LOOP
//main.appendChild(frag);
//version 3 - new DomParser()
let parser = new DOMParser();
let doc = parser.parseFromString(strHTML3, "text/html");
//doc.documentElement - whole HTML Document
console.log(doc.documentElement);
main.appendChild(doc.body.firstChild);
//version 4a - range.createContextualFragment()
let frag2 = document.createRange().createContextualFragment(strHTML4);
main.appendChild(frag2);
//version 4b - range.createContextualFragment()
let range = document.createRange();
range.setStart(main, 1); //after the one added with innerHTML
range.setEnd(main, 2);
let frag3 = range.createContextualFragment(strHTML5);
range.insertNode(frag3);
//version 5 - insertAdjacentHTML()
main.insertAdjacentHTML("afterbegin", strHTML6);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment