JS DOM - 01.01 - DOM

Manipulating DOM with JavaScript

Document Object Model (DOM)

DOM Living Standard.
The DOM represents all page content that can be modified.
The document object is the main “entry point” to the page. We can change or create anything on the page using it.

document.body.style.background = "red";

setTimeout( () => document.body.style.background = "", 1000);
// change the style back after 1 second.   "red" became ""

The browser builds up a model of the HTML document’s structure and uses this model to draw the page on the screen. This representation of the document’s structure that can be read or modified. It is a live data structure: when it’s modified, the page on the screen is updated to reflect the changes.

HTML is a set of boxes, For each box there is an object we can interact with to find out things such as what HTML tag it represents and which boxes and text it contains.
This representation is DOM.

DOM is tree like representation of contents of a webpage - a tree of “nodes” of different relationships depending on how they are arranged in the HTML document.

Browser Object Model (BOM)

The Browser Object Model (BOM) represents additional objects provided by the browser (host environment) for working with everything except the document.
The functions alert/confirm/prompt are also a part of the BOM: they are not directly related to the document, but represent pure browser methods for communicating with the user.
The BOM is a part of the general HTML specification.

Browser functions: setTimeoutalertlocation and so on.
navigator.userAgent – about the current browser, and navigator.platform – about the platform (can help to differentiate between Windows/Linux/Mac etc).


DOM tree

In DOM every HTML tag is an object.
Nested tags are “children” of the enclosing one.
The text inside a tag is an object as well.

The DOM represents HTML as a tree structure of tags, every tree node is an object.

Tags are element nodes (or just elements) and for the tree structure.
<html> is at the root, then <head> and <body> are its children.

The text inside elements form text nodes labeled as #text. It contains only string, it will not have children so always forms the leaf of the tree.

There are 12 node types. In practice we usually work with 4 of them:

  1. document – the “entry point” into DOM.
  2. element nodes – HTML-tags, the tree building blocks.
  3. text nodes – contain text.
  4. comments – sometimes we can put information there, it won’t be shown, but JS can read it from the DOM.