# Document Object Model

## Summary


Document Object Model (DOM) is the object-oriented representation of an HTML or XML document. It defines a platform-neutral programming interface for accessing various components of a webpage, so that JavaScript programs can change document structure, style, and content programmatically. 

It generates a hierarchical model of the HTML or XML document in memory. Programmers can access/manipulate tags, IDs, classes, attributes and elements using commands or methods provided by the document object. It's a logical structure because DOM doesn't specify any relationship between objects. 

Typically you use DOM API when documents can fit into memory. For very large documents, streaming APIs such as Simple API for XML (SAX) may be used.

The W3C DOM and WHATWG DOM are standards implemented in most modern browsers. However, many browsers extend these standards. Web applications must keep in view the DOM standard used for maintaining interoperability across browsers.

## Discussion

### What are the different components of a DOM?

Purpose of DOM is to mirror HTML/XML documents as an in-memory representation. It's composed of: 

    + Set of objects/elements
    + Hierarchical structure to combine objects
    + An interface to access/modify objectsDOM lists the required interface objects, with supported methods and fields. DOM-compliant browsers are responsible to supply concrete implementation in a particular language (mostly JavaScript).

Some HTML DOM objects, functions & attributes: 

    + **Node** - Each tree node is a Node object. Different types of nodes inherit from the basic `Node` interface.
    + **Document** - Root of the DOM tree is the HTMLDocument node. Usually available directly from JavaScript as document or window. Gives access to properties associated with a webpage such as URL, stylesheets, title, or characterSet. The field `document.documentElement` represents the child node of type `HTMLElement` and corresponds to `<html>` element.
    + **Attr** – An attribute in an `HTMLElement` object providing the ability to access and set an attribute. Has name and value fields.
    + **Text** — A leaf node containing text inside a markup element. If there is no markup inside, text is contained in a single `Text` object (only child of the element).

### Can you show with an example how a web page gets converted into its DOM?

The simplest way to see the DOM generated for any webpage is using "Inspect" option within your browser menu. DOM element navigation window that opens allows you to scroll through the element tree on the page. You can also alter some element values and styles – text, font, colours. Event listeners associated with each elements are also listed. 

The document is the root node of the DOM tree and offers many useful properties and methods. `document.getElementById(str)` gives you the element with `str` as id (or name). It returns a reference to the DOM tree node representing the desired element. Referring to the figure, `document.getElementById('div1')` will return the first "div" child node of the "body" node.

We can also see that "html" node has two direct children, "head" and "body". This example also shows three leaf nodes containing only text. These are one "title" and two "p" tags.

Corresponding CSS and JavaScript files referenced from HTML code can also be accessed through DOM objects. 


### How is JavaScript used to manipulate the DOM of a web page?

The ability to manipulate webpages dynamically using client-side programming is the basic purpose behind defining a DOM. This is achieved using DHTML. DHTML is not a markup language but a technique to make dynamic web pages using client-side programming. For uniform cross-browser support of webpages, DHTML involves three aspects:

    + **JavaScript** - for scripting cross-browser compatible code
    + **CSS** - for controlling the style and presentation
    + **DOM** - for a uniform programming interface to access and manipulate the web page as a documentGoogle Chrome, Microsoft Edge, Mozilla Firefox and other browsers support DOM through standard JavaScript. JavaScript programming can be used to manipulate the HTML page rendering, the underlying DOM and the supporting CSS. List of some important DOM related JavaScript functionalities: 

    + Select, Create, Update and Delete DOM Elements (reference by ID/Name)
    + Style setting of DOM Elements – color, font, size, etc
    + Get/set attributes of Elements
    + Navigating between DOM elements – child, parent, sibling nodes
    + Manipulating the BOM (Browser Object Model) to interact with the browser
    + Event listeners and propagation based on action triggers on DOM elements

### Can DOM be applied to documents other than HTML or XML?

By definition, DOM is a language-neutral object interface. W3 clearly defines it as an API for valid HTML and well-formed XML documents. Therefore, a DOM can be defined for any XML compliant markup language. The WHATWG community manages the HTML DOM interface. Some Microsoft specific XML extensions define their own DOM. 

**Scalable Vector Graphics (SVG)** is an XML-based markup language for describing two-dimensional vector graphics. It defines its own DOM API. 

**XAML** is a declarative markup language promoted by Microsoft, used in UI creation of .NET Core apps. When represented as text, XAML files are XML files with `.xaml` extension. By treating XAML as a XAML node stream, XAML readers communicate with XAML writers and enable a program to view/alter the contents of a XAML node stream similar to the XML Document Object Model (DOM) and the `XmlReader` and `XmlWriter` classes.  

**Standard Generalized Markup Language (SGML)** is a standard for how to specify a document markup language or tag set. The DOM support for SGML documents is limited to parallel support for XML. While working with SGML documents, the DOM will ignore `IGNORE` marked sections and `RCDATA` sections. 


### What are the disadvantages of using DOM?

The biggest problem with DOM is that it is **memory intensive**. While using the DOM interface, the entire HTML/XML is parsed and a DOM tree (of all nodes) is generated and returned. Once parsed, the user can navigate the tree to access data in the document nodes. DOM interface is easy and flexible to use but has an overhead of parsing the entire HTML/XML before you can start using it. So when the document size is large, the memory requirement is high and initial document loading time is also high. For small devices with limited on board memory, DOM parsing might be an overhead. 

SAX (Simple API for XML) is another document parsing technique where the parser doesn’t read in the entire document. Events are triggered when the XML is being parsed. When it encounters a tag start (e.g. `<sometag>`), then it triggers the tagStarted event. When the end of the tag is seen (`</sometag>`), it triggers tagEnded. So it's better in terms of memory efficiency for heavy applications. 

In earlier days, the DOM standard was not uniformly adopted by various browsers, but that incompatibility issue doesn’t exist anymore. 


### What sort of DOM support is offered by React, Node.js and other JavaScript-based platforms?

Everything in DOM is a node – document/element/attribute nodes, etc. But if you have a list of 10 items on your webpage and after some user interaction, need to update one of them, the entire DOM will be re-rendered. This is especially troublesome in Single Page Applications (SPAs).

React WebUI framework solves this by creating a **virtual DOM** which is an in-memory data-structure cache for selective rendering. Differences in the node rendering are computed, browser's displayed DOM is updated efficiently, "reconciled" by the algorithm. 

NodeJS runtime environment has its own implementation for DOM interface, used when we need to work with HTML on server side for some reason. The DOM `Node` interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. `jsdom` is a pure JavaScript implementation of WHATWG DOM and HTML Standards for use with Node.js.   

In AngularJS scripting framework, there are directives for binding application data to attributes of HTML DOM elements. Ex. `ng-disabled` directive binds AngularJS application data to the disabled attribute of HTML elements. 

## Milestones

1995

Brendan Eich and Netscape design and release JavaScript, first supported in Netscape Navigator. In subsequent years, JavaScript becomes one of the core technologies of the World Wide Web, alongside HTML and CSS. All major web browsers have a dedicated JavaScript engine to execute it. In 1997, it's standardized as ECMAScript. 

1996

JScript is introduced as the Microsoft dialect of the ECMAScript standard. Limited support for user-generated events and modifying HTML documents in the first generation of JavaScript & JScript is called "DOM Level 0" or **Legacy DOM**. No independent standard is developed for DOM Level 0, but it's partly described in the specifications for HTML 4. 

1997

Netscape and Microsoft release version 4.0 of Netscape Navigator and Internet Explorer respectively. DHTML support is added to enable changes to a loaded HTML document. DHTML requires extensions to Legacy DOM implementations but both browsers developed them in parallel and remain incompatible. These versions of the DOM later become known as the **Intermediate DOM**. 

1998

W3C DOM Working Group drafts a standard DOM specification, known as **DOM Level 1** that becomes the W3C Recommendation in 1998. This is after the standardization of ECMAScript. 

2001

Microsoft Internet Explorer version 6 comes out with support for W3C DOM. 

2004

Mozilla comes out with its *Design Principles for Web Application Technologies*, the consensus opinion of the Mozilla Foundation and Opera Software in the context of standards for Web Applications and Compound Documents. This defines browser code compatibility with HTML, CSS, DOM, and JavaScript. 

2005

Large parts of W3C DOM are well-supported by all the common ECMAScript-enabled browsers including Safari and Gecko-based browsers (like Mozilla, Firefox, SeaMonkey and Camino). 

2020

The HTML DOM living standard is a constantly updated standard maintained by WHATWG.org, with latest updates happening continuously.