Modifying The Document

Creating an element

document.createElement(tag)

let div = document.createElement("div");

document.createTextNode(text)

let textNode = document.createTextNode("Lmao");

Insertion method

document.body.append(div);

insertAdjacentHTML / Text / Element

elem.insertAdjacentHTML(where, html)

The first parameter is a code word, specifying where to insert relative to elem. Must be one of the following:

The method has 2 brothers:

Node removal

elem.remove();

All insertion methods automatically remove the node from the old place

Cloning nodes: cloneNode

The call elem.cloneNode(true) creates a deep clone of the element - with all attributes and subelements. If we call elem.cloneNode(false), then the clone is made without child elements.

let div2 = div.cloneNode(true); // clone the existing div
div2.querySelector("b").innerHTML = "Bye there!"; // change the clone

div.after(div2); // show the clone after the existing div

DocumentFragment

DocumentFragment is a special DOM node that servers as a wrapper to pass around lists of nodes. We canappend other nodes to it, but when we insert it somewhere, then its content is inserted instead.

<ul id="ul"></ul>

<script>
  function getListContent() {
    let fragment = new DocumentFragment();

    for (let i = 1; i <= 3; i++) {
      let li = document.createElement("li");
      li.append(i);
      fragment.append(li);
    }

    return fragment;
  }

  ul.append(getListContent()); // (*)
</script>

At the last line (*) we append DocumentFragment, but it blends in, so the resulting structure will be:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

DocumentFragment is rarely used explicitly. We mention it mainly because there are some concepts on top of it, like template element, that we'll cover much later.