Document Object Model(DOM)
The document loaded in browser will be interpreted into a tree-structured object, which is represented as DOM. DOM provide interfaces and methods for accessing and manipulating the nodes in the tree after the document is rendered(otherwise the target does not exist in the tree). For example, a document could be represented as the below tree:
|DOCTYPE html
|--html
|--head
|--#text
|--title
|--#text:DOM Manipulation
|--#text
|--#text
|--body
|--#text
|--p class="para"
|--#text
|--#text
Nodes in a tree could be:
- Element Node: Node.ELEMENT_NODE, an element like <div>
, <p>
- Text Node: Node.TEXT_NODE, the text element inside an element node
- Comment Node: Node.COMMENT_NODE, a comment node
There are other nodes, i.e, Node.DOCUMENT_NODE, Node.DOCUMENT_TYPE_NODE, Node.DOCUMENT_FRAGMENT_NODE.
Node
interface is used to manipulate on the tree structure, like creating, removing, replacing nodes in the tree. There’s another interface Element
, which inherits from Node
, and derives a lot of child element interfaces. Element
is used to manipulate element attributes. But we always get the HTMLxxxElement
so we could invoke Node methods for DOM tree manipulation invoke Element methods for attributes.
EventTarget <- Node <- Element <- HTMLElement <- HTMLBodyElement
<- Attr <- HTMLDivElement
<- Document ...
...
Node And NodeList
Node
is an interface inherit fromEventTarget
. It’s the parent interface for many other interfaces and mainly provide properties and methods for traversing.NodeList
is the collection ofNode
, which is array-like interface. It’s iterable and convenient to convert toArray
.
Traverse Node
Node.childNodes
: a read-only property returns a live collection of child nodes of the given element where the first child node is assigned index 0.Node.childNodes
includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, useParentNode.children
instead.Element.children
a read-only property that returns a liveHTMLCollection
which contains all of the child elements of the node upon which it was called.Node.parentNode
returns aNode
that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn’t participate in a tree, this property returns null.Node.parentElement
returns anElement
that is the parent of this node. If the node has no parent, or if that parent is not anElement
, this property returns null.Node.firstChild
returns aNode
representing the first direct child node of the node, or null if the node has no child.Node.lastChild
returns aNode
representing the last direct child node of the node, or null if the node has no child.Node.previousSibling
returns aNode
representing the previous node in the tree, or null if there isn’t such node.Node.nextSibling
returns aNode
representing the next node in the tree, or null if there isn’t such node.
Accessing Element
Element.querySelector('selector')
andElement.querySelectorAll('selector')
are the convenient ways to select the target element.Element.querySelector('selector')
returns the first matched element child node whileElement.querySelectorAll('selector')
returns a NodeList containing all matched element child nodes. There are also old methods likeElement.getElementById('id')
andElement.getElementsByTagName('tag')
, which are not convenient for DOM element selection.
Creating Node
To create three common-used nodes, “Element Node”, “Text Node” and “Comment Node”, DOM provides corresponding methods.
- document.createElement('tagName')
creates a Element Node.
- document.createTextNode('text')
creates a new Text Node.
- document.createComment('comment')
creates a Comment Node.
- Node.cloneNode([deep])
clone a Node
, and optionally, all of its contents. By default, it clones the content of the node. Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()
or those assigned to element properties (e.g. node.onclick = fn
). Moreover, for a <canvas>
element, the painted image is not copied. The duplicate node returned by cloneNode()
is not part of the document until it is added to another node that is part of the document using Node.appendChild()
or a similar method. It also has no parent until it is appended to another node. If deep
evaluates to true, the whole subtree (including text that may be in child Text nodes) is copied too.
Modifying Node
Node.appendChild(childNode)
adds thechildNode
(must be Node type) to the end of the current node and return the appendedchildNode
. IfchildNode
is an existing node in document, it will be removed from it current position to a new position.Node.insertBefore(newNode, refNode)
insert thenewNode
before therefNode
as a child of the current node. IfnewNode
is a reference to an existing node in the document, insertBefore() moves it from its current position to the new position. IfrefNode
is null, it append thenewNode
to the end of child list, as theappendChild
does.Node.removeChild(childNode)
remove thechildNode
from the current node and return the removedchildNode
ifchildNode
exists. Otherwise, it throws errors.Node.replaceChild(newChild, oldChild)
replace theoldChild
withnewChild
and return theoldChild
. IfoldChild
does not exist or is not the child of current node, it will throw error.
Manipulating Styles
HTMLElement.style.** =
to set inline styles for the element
Class Manipulation
Element.setAttribute('class', 'className')
to set classes for the element(orElement.className
)Element.removeAttribute('class')
to remove all classes from the elementElement.classList
interface for class manipulation. It’s supported by IE 10+