DOM distilled

Simple case

<p>foo</p>

A single p element whose content is the text foo.

// Create the element
const e = document.createElement("p");

// Append its content.
e.append("foo");

// Append the element to the body so it appears on the page
body.append(e);

Nested elements

<p>Some <i>emphasized</i> text</p>

Two elements: p and i. Also text in both the p and is.

const paragraph = document.createElement("p");
const italic = document.createElement("i");

italic.append("emphasized");
paragraph.append("Some ", italic, " text.");
body.append(paragraph);

Nested elements 2

<ol>
  <li>Apples</li>
  <li>Bananas</li>
</ol>

Three elements: one ol and two li.

const list = document.createElement("ol");

const item1 = document.createElement("li");
item1.append("Apples");

const item2 = document.createElement("li");
item2.append("Bananas");

list.append(item1, item2);

body.append(list);

Empty element

<img src="kittens.jpg" alt="cute kittens">

One element: img. No content.

Two attributes: src and alt.

const image = document.createElement("img");
image.setAttribute("src", "kittens.jpg");
image.setAttribute("alt", "cute kittens");

body.append(image);

Class attribute

<p class="warning">Don't feed the bears</p>

One element: p.

One attribute: class.

const paragraph = document.createElement("p");
paragraph.append("Don't feed the bears");
paragraph.classList.add("warning");

body.append(paragraph);

Attribute and content

<div id="acknowledgments">
  <p>Thanks to my parents, Ayn Rand and God</p>
  <p>Also I'd like to thank the Academy.</p>
</div>

Three elements: div and two p; and one attribute: id.

const d1 = document.createElement("div");
d1.setAttribute("id", "acknowledgments");

const p1 = document.createElement("p");
p1.append("Thanks to my parents, Ayn Rand and God");

const p2 = document.createElement("p");
p2.append("Also I'd like to thank the Academy.");

d1.append(p1, p2);

body.append(d1);

Advanced mode

First: write a function

const add = (parent, tag, content) => {
  // Make an element of the given type
  const e = document.createElement(tag);

  // If content was provided, append it.
  if (content) {
    e.append(content);
  }

  // Add the element to the provided parent
  parent.append(e);

  // And return the new element
  return e;
};

Use the function

<div id="acknowledgments">
  <p>Thanks to my parents, Ayn Rand and God</p>
  <p>Also I'd like to thank the Academy.</p>
</div>

Same HTML as two slides ago.

Now build it using our add function.

const d1 = add(body, 'div');
d1.setAttribute("id", "acknowledgments");

add(d1, "p", "Thanks to my parents, Ayn Rand and God");
add(d1, "p", "Also I'd like to thank the Academy.");