Creating and removing nodes

A page that shows data has to build its elements: one for each record, with the text and the attributes of that record, put into a list or a table. The DOM builds them out of thin air with createElement, joins them with append and its neighbours, and takes them out again with remove. Nothing is parsed on that path, which is what makes it the safe way to render a value that came from a reader.

The four programs of this lesson build one list, insert an element in the middle of it, take one out and then render the whole list from an array twice. They run on pages opened by jsdom as the first lesson of this part showed, and they print counts, texts and the serialised markup of a single element.

createElement and append

document.createElement('li') makes an element that belongs to the document but sits nowhere in it, and append puts nodes at the end of a parent. The method takes any number of nodes and strings, so a text node and an element can go in one call, and it moves a node that is already somewhere else rather than copying it. Until the append the new element has no parent, and that is the difference between an element that exists and an element that a page shows.

The program builds one item, appends it, appends a second one with a text node, and prints the counts.

The file create.js:

const { JSDOM } = require('jsdom'); const html = '<!doctype html><body><ul id="list"></ul></body>'; const dom = new JSDOM(html, { url: 'http://localhost/' }); const { document } = dom.window; const list = document.querySelector('#list'); const item = document.createElement('li'); item.textContent = 'first'; item.className = 'item'; list.append(item); console.log('items after the append:', list.children.length); console.log('the new item:', item.outerHTML); console.log('its parent:', item.parentElement.id); const second = document.createElement('li'); second.textContent = 'second'; list.append(second, ' and a text node'); console.log('after a second append:', list.children.length); console.log('the text of the list:', list.textContent); console.log('a text node is not an element:', list.childNodes.length);

node create.js

items after the append: 1
the new item: <li class="item">first</li>
its parent: list
after a second append: 2
the text of the list: firstsecond and a text node
a text node is not an element: 3

Two elements and three nodes: the string in the second append became a text node beside the element, and children does not count it. The serialised item shows the class and the text in the order the program set them, which is the markup a reader of the page receives.

insertBefore and its neighbours

insertBefore(node, reference) puts a node in front of an existing child and returns the node it inserted. With null as the reference it appends at the end, which is why the two are one method with two modes. The newer names read better: prepend at the start of a parent, before and after around a node, and append at the end.

The program keeps one list in order while it inserts at the front, in the middle and at the end, and prints the order after each step.

The file insert.js:

const { JSDOM } = require('jsdom'); const html = '<!doctype html><body><ul id="list"><li>one</li><li>three</li></ul></body>'; const dom = new JSDOM(html, { url: 'http://localhost/' }); const { document } = dom.window; const list = document.querySelector('#list'); const two = document.createElement('li'); two.textContent = 'two'; const appended = list.insertBefore(two, list.children[1]); console.log('insertBefore returns the node:', appended === two); console.log('the order now:', Array.from(list.children).map((li) => li.textContent).join(', ')); const zero = document.createElement('li'); zero.textContent = 'zero'; list.prepend(zero); console.log('after prepend:', Array.from(list.children).map((li) => li.textContent).join(', ')); const four = document.createElement('li'); four.textContent = 'four'; list.children[1].after(four); console.log('after after:', Array.from(list.children).map((li) => li.textContent).join(', ')); const last = document.createElement('li'); last.textContent = 'last'; list.insertBefore(last, null); console.log('insertBefore with null appends:', Array.from(list.children).map((li) => li.textContent).join(', '));

node insert.js

insertBefore returns the node: true
the order now: one, two, three
after prepend: zero, one, two, three
after after: zero, one, four, two, three
insertBefore with null appends: zero, one, four, two, three, last

Each call put the new element exactly where the program asked, and the reference child decided the position. The insert in the last line took the place of the reference, so it landed at the end, which makes insertBefore(node, null) and append(node) the same operation with two spellings.

remove and replaceChildren

remove() takes a node out of its parent, and a node that has no parent is a no-op: the second call is quiet, which makes the method safe to call from a handler that may run twice. The older parent.removeChild(node) is not quiet, because it insists that the node is a child. replaceChildren() with no arguments empties an element in one call, and with arguments it empties it and fills it again.

The program removes the sold item, removes it again, asks the strict method for the same node and then empties the list.

The file remove.js:

const { JSDOM } = require('jsdom'); const html = '<!doctype html><body><ul id="list"><li>one</li><li class="sold">two</li><li>three</li></ul></body>'; const dom = new JSDOM(html, { url: 'http://localhost/' }); const { document } = dom.window; const list = document.querySelector('#list'); const sold = list.querySelector('.sold'); sold.remove(); console.log('items after the remove:', list.children.length); console.log('sold items left:', list.querySelectorAll('.sold').length); console.log('the removed node still has its text:', sold.textContent); console.log('but no parent:', sold.parentElement); sold.remove(); console.log('a second remove is quiet:', list.children.length); try { list.removeChild(sold); } catch (error) { console.log('the error:', error.name, '-', error.message); } const all = list.replaceChildren(); console.log('after replaceChildren:', list.children.length, 'the return value:', all);

node remove.js

items after the remove: 2
sold items left: 0
the removed node still has its text: two
but no parent: null
a second remove is quiet: 2
the error: NotFoundError - The node to be removed is not a child of this node.
after replaceChildren: 0 the return value: undefined

The node survived the removal with its text and lost its parent, so a program can still read it, change it and put it back somewhere else. The error is the price of the older method: it checks the parent before it acts, while remove and replaceChildren do what their names say and answer with nothing.

A list rendered from data

A render function takes a container and an array and puts one element per record into the container. The first line is the one that makes it repeatable: replaceChildren() empties the container, so a second render does not add a second copy of every item. The text of a record goes in through textContent, and the id goes into a data attribute, which is the pair from the previous lesson used on a whole list.

The program renders three notes, then renders the two that are left after a filter, and prints the count, the text and the markup of the first item.

The file render.js:

const { JSDOM } = require('jsdom'); const html = '<!doctype html><body><h1>Notes</h1><ul id="notes"></ul><p id="count"></p></body>'; const dom = new JSDOM(html, { url: 'http://localhost/' }); const { document } = dom.window; const notes = [ { id: 1, title: 'first note', done: true }, { id: 2, title: 'second note', done: false }, { id: 3, title: 'third note', done: false }, ]; function render(list, notes) { list.replaceChildren(); for (const note of notes) { const item = document.createElement('li'); item.className = note.done ? 'note done' : 'note'; item.dataset.id = String(note.id); const title = document.createElement('span'); title.textContent = note.title; item.append(title); list.append(item); } } const list = document.querySelector('#notes'); render(list, notes); console.log('the items:', list.children.length); console.log('the text:', Array.from(list.children).map((li) => li.textContent).join(' | ')); console.log('the first item:', list.firstElementChild.outerHTML); console.log('the done ones:', list.querySelectorAll('.done').length); render(list, notes.filter((note) => !note.done)); console.log('after a second render:', list.children.length); console.log('the text now:', Array.from(list.children).map((li) => li.textContent).join(' | ')); document.querySelector('#count').textContent = `${list.children.length} of ${notes.length}`; console.log('the counter:', document.querySelector('#count').textContent);

node render.js

the items: 3
the text: first note | second note | third note
the first item: <li class="note done" data-id="1"><span>first note</span></li>
the done ones: 1
after a second render: 2
the text now: second note | third note
the counter: 2 of 3

The second render has two items and not five, and the count went into the page as text through textContent. The markup of the first item is the whole recipe of this lesson in one line: a class from the data, an attribute from the data, and a child element whose text came from a string that no parser ever saw.

Exercises

  1. Append an element that is already in the list a second time. Does the list grow, and what does the count say?
  2. Build an item with document.createElement and read outerHTML before the append. What does the page show, and what does the string show?
  3. Insert a node before the first child of the list with prepend and with insertBefore(node, list.firstElementChild). Are the two positions the same?
  4. Render the notes with textContent replaced by innerHTML and give one title the value <b>bold</b>. What changes in the output?
  5. Add a counter of the render calls and print it after the second render. Why is the counter not in the page itself?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which method makes an element that is not on the page yet?

    Answer

    document.createElement

    createElement builds the node in memory, and it joins the page at the first append.

  2. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul id=list></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("#list"); list.append(dom.window.document.createElement("li")); list.append(dom.window.document.createElement("li")); console.log(list.children.length);

    Answer

    2

    append puts each new element at the end of the list, and children counts both of them.

  3. What does insertBefore(node, null) do?

    Answer

    It appends the node at the end of the parent

    There is no reference child, so the new node goes last, which is the same as append.

  4. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li>one</li><li>three</li></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("ul"); const two = dom.window.document.createElement("li"); two.textContent = "two"; list.insertBefore(two, list.children[1]); console.log(Array.from(list.children).map((li) => li.textContent).join(", "));

    Answer

    one, two, three

    The reference was the second child, so the new element took its place and pushed it back.

  5. What does remove() do on a node that is not in the document?

    Answer

    Nothing, and it throws no error

    remove asks for a parent and finds none, so there is nothing to do and no reason to fail.

  6. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li>one</li></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("ul"); try { list.removeChild(dom.window.document.createElement("li")); } catch (error) { console.log(error.name); }

    Answer

    NotFoundError

    The strict method checks that the node is a child of this parent and refuses a stranger.

  7. What does replaceChildren() with no arguments do?

    Answer

    It removes every child of the element

    No children in the argument list means no children left inside the element.

  8. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li>old</li></ul>", { url: "http://localhost/" }); const list = dom.window.document.querySelector("ul"); const one = dom.window.document.createElement("li"); one.textContent = "one"; const two = dom.window.document.createElement("li"); two.textContent = "two"; list.replaceChildren(one, two); console.log(list.children.length, list.firstElementChild.textContent);

    Answer

    2 one

    The old child went with the replace, and the two new ones took its place in order.

  9. Why does a render function start with replaceChildren()?

    Answer

    So a second render replaces the first instead of adding to it

    The empty container is what makes one render idempotent, whatever the previous state was.

  10. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li class=sold>one</li></ul>", { url: "http://localhost/" }); const item = dom.window.document.querySelector(".sold"); item.remove(); console.log(item.textContent, item.parentElement);

    Answer

    one null

    The node keeps its text after the removal and loses its parent, which is what the second word says.

The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image