Member-only story

Notes on JavaScript DOM Tree

Observations of tools and practices for frontend development

--

Another story on web development with written form the perspective of a native GUI developer. This story will focus more on JavaScript and DOM tree manipulation in general. How do we use events, queries, templates etc.

I have already covered more of the backend development side in previous articles as well as the HTTP protocol:

Frontend Development HTML, CSS and Chrome

This article will instead focus more on the frontend part, but will mostly be in note form.

Nodes vs Elements

In the DOM model a Node is an abstract type. You cannot actually make Node objects. What you think of as HTML tags are of type Element. Less obvious is perhaps the the text itself inside Elements is actually a Node subtype named Text. Node has all the methods for moving up and around the DOM tree.

When we implement our own element we usually subclass HTMLElement, which is a subclass of Element.

append VS appendChild

Given a parent node p and a child node n we can write both p.append(n) and p.appendChild(n). The latter always requires a Node subtype and returns this object to allow chaining. The former, can add both strings and nodes, but doesn't return anything. It can also be used to add multiple elements.

Conclusion: appendChild is probably the preferable one most of the time.

The DOM and the querySelector

A couple of useful observations of things you could easily miss. You typically see querySelector used like this:

document.querySelector("#tellus")

But there is nothing special about document. It is just the first Node in the DOM tree. You can query from any node. Hence you can just as well write:

document.body.children[3].querySelector("i")

Also keep in mind that querySelector always gives a single result. If you want more matches you use…

--

--

Erik Engheim
Erik Engheim

Written by Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

No responses yet

Write a response