DOM Elements versus HTML markup

A good analogy to understand the relationship of DOM elements to HTML is to think of them like being the proteins which are created from DNA:

  • HTML is the DNA - the instructions given as to what elements to create on the page.

  • DOM elements are the proteins which are actually created at runtime. These live in memory data-structures which represent the entire state of HTML markup, live in the browser. Under the hood they are going to be implemented in C/C++ as objects with state. There is going to be a lot of state - lots of data is required to represent the state of single ‘tag’ in a live document.

Most of the time DOM elements live in a tree under the main document element of the page. However they can be created outside of that tree. Libraries like jQuery will create DOM elements for you when you call them with a string containing HTML markup.

It helps conceptually if you try out this process for yourself using the raw built in Javascript APIs of the browser:

var x = document.createElement("p"); x.innerText = "Hello world" document.children[0].append(x)

This shows the raw APIs for how we can create an element, set a property and then show it by appending it the first child DOM element of the document.