Document Object Model (DOM)

DOM stands for Document Object Model, which is a representation of HTML documents in nodes and objects. The browser exposes an API that can be used to interact with the DOM. This is how modern JavaScript frameworks work-they use the DOM API to tell the browser what to display on the page

DOM is the browser's internal representation of web pages. When the browser retrieves HTML from the server, the parser will analyze the structure of the code and create a model for it. Then, based on this model, the browser renders the page on the screen.

The browser exposes an API that can be used to interact with the DOM. This is how modern JavaScript frameworks work-they use the DOM API to tell the browser what to display on the page.

In a "single page application", the DOM is constantly changing to reflect what is displayed on the screen. As a developer, you can useBrowser developer tools.

DOM has nothing to do with language. In fact, the standard for accessing DOM is through the use ofJavaScript, Because it is the only language that the browser can run.

DOM by WHATWG inDOM Living Standard Specification.

Using JavaScript, you can interact with the DOM to:

  • Check page structure
  • Access page metadata and title
  • Edit CSS style
  • Attach or remove event listeners
  • Edit any node in the page
  • Change any node properties

.. and more.

The main 2 objects provided by the DOM API that you will interact with the most aredocumentwithwindow.

Window object

ThiswindowThe object represents the window containing the DOM document.

window.documentdirectiondocumentThe object is loaded into the window.

Call the properties and methods of the object without referencewindowExplicit, because it represents the global object. Therefore, the previous attributeswindow.documentusually calleddocument.

characteristic

This is a list of useful attributes, and you may refer to them frequently:

  • consolePoint to the browser debug console. It is useful to print error messages or records using the following commandconsole.log,console.errorAnd other tools (seeBrowser development toolsarticle)
  • documentAs mentioned before, point todocumentObject, the key to the DOM interaction you will perform
  • historyAllow accessHistory API
  • locationAllow accessPositioning interface, From which you can determine the URL, protocol, hash and other useful information.
  • localStorageis trueWeb Storage APIlocalStorage object
  • sessionStorageIs a reference to the Web Storage API sessionStorage object

method

ThiswindowThe object also exposes useful methods:

  • alert(): Can be used to display the alert dialog
  • postMessage():byChannel Message API
  • requestAnimationFrame(): Used to execute animation on the CPU in an efficient and easy way
  • setInterval(): The function is called every n milliseconds until the clear interval is usedclearInterval()
  • clearInterval(): Clear the interval created usingsetInterval()
  • setTimeout(): Execute function after "n" milliseconds
  • setImmediate(): Execute the function as soon as the browser is ready
  • addEventListener(): Add the event listener to the document
  • removeEventListener(): Remove the event listener from the document

See the complete reference of all properties and methods.windowOpposehttps://developer.mozilla.org/zh-CN/docs/Web/API/Window

Document object

ThisdocumentThe object represents the DOM tree loaded in the window.

This is part of the DOM pointing to the head and body tags:

DOM, the body and head tags

This is a partial representation of the DOM, showing the head tag, which contains the title tag with its value:

DOM, the head tag with the title

This is a representation of a part of the DOM, which shows the body tag, which contains a link with a value and an href attribute with its value:

DOM, the body tag with a link

The Document object can be accessed fromwindow.document,as well aswindowIs a global object, you can use shortcutsdocumentFind the object directly from the browser console or JavaScript code.

The Document object has a large number of properties and methods. ThisSelector APIMethod is the method you are most likely to use:

  • document.getElementById()
  • document.querySelector()
  • document.querySelectorAll()
  • document.getElementsByTagName()
  • document.getElementsByClassName()

You can use to get the file titledocument.title, URL usedocument.URL. Referrer URL isdocument.referrer, The domain indocument.domain.

FromdocumentYou can get body and head objectsElement node:

  • document.documentElement: "Documents" node
  • document.body: ThisbodyElement node
  • document.head: ThisheadElement node

The DOM nodes

You can also get a list of all element nodes of a specific type, for exampleHTMLCollectionUsed in all linksdocument.links, All images usedocument.images, All forms usedocument.forms.

fileBiscuitCan be accessed in the following locationsdocument.cookie. Last modified datedocument.lastModified.

You can do more and even getOld-fashionedAnd usedocument.write(), This method was used extensively in the early days of JavaScript to interact with the page.

See the complete reference of all properties and methods.documentOpposehttps://developer.mozilla.org/zh-CN/docs/Web/API/Document

Node type

There are different types of nodes, some of which have been seen in the example image above. The main problems you will encounter are:

  • Documentation: Document node, the beginning of the tree
  • element: HTML tags
  • Attr: The attributes of the label
  • text: The text content of the element or attribute node
  • comment: HTML comments
  • file type: Thisfile typedeclaration

Traverse the DOM

DOM is an element tree, and its "document" node is located at the root node, which points tohtmlElement node, which in turn points to its child element nodesheadwithbody, and many more.

From each of these elements, you can navigate the DOM structure and move to different nodes.

Get parents

Every element hasonly oneparents

To get it, you can useNode.parentNodeorNode.parentElement(Node represents a node in the DOM).

They are almost the same, except inhtmlelement:parentNodeReturns the parent of the specified node in the DOM tree, andparentElementReturns the parent element of the DOM node; if the node has no parent element or its parent element is not a DOM element, then null is returned.

People usually useparentNode.

Let the kids

To check whether a node has child nodes, useNode.hasChildNodes()Returns a boolean value.

To access all child element nodes of the node, useNode.childNodes.

DOM also made publicNode.childrenmethod. However, it includes not only element nodes, but also white space between elements as text nodes. This is not what you usually want.

Get the children of a node

To get the first child element node, useNode.firstElementChild. To get the last child element node, useNode.lastElementChild:

To get the first or last child Element Node

DOM also made publicNode.firstChildwithNode.lastChild, The difference is that they will not only "filter" the tree for the "element" node. They will also display blank Text nodes indicating blanks.

In short, to navigate the child element nodes use

  • Node.childNodes
  • Node.firstElementChild
  • Node.lastElementChild

Get siblings

In addition to getting the parent and child, since the DOM is a tree, you can also get the siblings of any element node.

you can use it

  • Node.previousElementSibling
  • Node.nextElementSibling

DOM also made publicpreviousSiblingwithnextSibling, But as mentioned above, they include spaces as Text nodes, so they should generally be avoided.

Edit the DOM

DOM provides a variety of methods to edit the nodes of the page and change the document tree.

with

  • document.createElement(): Create a new element node
  • document.createTextNode(): Create a new text node

You can create a new element and add it to the DOM element you want to be a child element by usingdocument.appendChild():

const div = document.createElement('div')
div.appendChild(document.createTextNode('Hello world!'))
  • first.removeChild(second)Delete the child node "Second" from the node "First".
  • document.insertBefore(newNode, existingNode)Insert "newNode" as the sibling of "existingNode" and place it in the DOM tree structure.
  • element.appendChild(newChild)Change the tree under "element" and add a new child node "newChild" after all other child nodes.
  • element.prepend(newChild)Change the tree under "element" and add a new child node "newChild" to it before other child elements. You can pass one or more child nodes, or even a string, which will be interpreted as a "text" node.
  • element.replaceChild(newChild, existingChild)Change the tree under "Elements" and replace "existingChild" with the new node "newChild".
  • element.insertAdjacentElement(position, newElement)Insert "newElement" into the DOM and position it relative to "element" according to the value of the "position" parameter.View possible values.
  • element.textContent = 'something'Change the content of the "Text" node to "Something".

Download mine for freeJavaScript beginner's manual


More browser tutorials: