DOM API
- Node
- Element
- property
- methods
- DocumentFragment
- The Document type
- Selector API
- Viewport
- Event
- event flow
event.target
event.currentTarget
event.eventPhase
- creating
CustomEvent
Node
- A
node
is the generic name for any type of object in the DOM hierarchy. - A node could be one of the built-in DOM elements such as
document
ordocument.body
. it could be an HTML tag specified in the HTML such as<input>
or<p>
or it could be a text node that is created by the system to hold a block of text inside another element. - a node is any DOM object
Node Type | number |
---|---|
Node.ELEMENT_NODE |
1 |
Node.ATTRIBUTE_NODE |
2 |
Node.TEXT_NODE |
3 |
Node.CDATA_SECTION_NODE |
4 |
Node.ENTITY_REFERENCE_NODE |
5 |
Node.ENTITY_NODE |
6 |
Node.PROCESSING_INSTRUCTION_NODE |
7 |
Node.COMMENT_NODE |
8 |
Node.DOCUMENT_NODE |
9 |
Node.DOCUMENT_TYPE_NODE |
10 |
Node.DOCUMENT_FRAGMENT_NODE |
11 |
Node.NOTATION_NODE |
12 |
modify itself
node.remove()
: removes the object from the tree it belongs to.node.cloneNode(shouldDeepCopy)
- if
shouldDeepCopy
sets to true, the method will copy childNodes as well. .cloneNode()
doesn't copy JavaScript properties that you added to DOM nodes, such as event handlers. It only copies attributes and optionally, childNodes.
- if
node.append()
- The
ParentNode.append
method inserts a set ofNode
objects orDOMString
objects after the last child of the ParentNode.DOMString
objects are inserted as equivalentText
nodes.- Polyfill Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md
- The
with children nodes
node.children
- a read-only property that returns a live
HTMLCollection
of the child elements of Node. Node.children
is an array-like object.- To convert it to an array
var childrenNode = divElement.children; var childrenNodeList = []; for (let i = 0; i < childrenNode.length; i += 1) { childrenNodeList.push(childrenNode[i]); }
- a read-only property that returns a live
node.childNodes
node.firstChild
node.lastChild
node.hasChildNodes()
node.replaceChild(oldNode, newNode)
node.removeChild(node)
node.appendChild()
- It adds a node to the end of the list of children of a specified parent node.
- If the given child is a reference to an existing node in the document, it moves it from its current position to the new position.
- If needed, use
Node.cloneNode()
to get a copy, and use.appendChild()
method
node.insertBefore(nodeToInsert, referenceNode)
- if
referenceNode
isnull
, it acts likeappendChild()
- if
With neighbor nodes
node.nextSibling
node.previousSibling
With parent node
node.parentNode
With elements
node.parentElement
node.nextElementSibling
node.previousElementSibling
node.parentNode
vs node.parentElement
- In most cases, it is the same as parentNode.
- The only difference comes when a node's parentNode is not an element. If so, parentElement is null.
HTMLElement vs Node
Element
- An
element
is one specific type of node. - And there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).
Property
Element.id
Element.classList
- return
DOMTokenList
- return
Element.classNames
- return
DOMString
- return
Element.innerHTML
Element.tagName
Element.style
HTMLElement.dataset
: accessdata-*
- access with camelCase
data-member-id
asdataset.memberId
Methods
Element.getAttribute(attributeName)
Element.hasAttribute(attributeName)
Element.removeAttribute(attributeName)
Element.setAttribute(attributeName, attributeValue)
Element.querySelector()
Element.querySelectorAll()
position & viewport
Element.getBoundingClientRect()
TheElement.getBoundingClientRect()
method returns the size of an element and its position relative to the viewport.ClientRect { top: -110, right: 672, bottom: -29, left: 0, width: 672 }
Element.clientHeight
&Element.clientWidth
Element.offsetTop
calculates the offset from itsoffsetParent
DocumentFragment
The key difference is that because the document fragment isn't part of the actual DOM's structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made.
DocumentFragment
继承了Node
的所有方法,通常用于执行那些针对document的DOM操作。
var fragment = document.createDocumentFragment();
The Document type
Document
represents the document node.
nodeName
:#document
nodeValue
:null
parentNode
:null
document.body
refers to<body>
elementdocument.documentElement
refers to<html>
elementdocument.title
refers to the page titledocument.URL
document.domain
Selector API
- querySelector()
- querySelectorAll()
- matchesSelector()
check if an element would be returned by querySelectorAll
or querySelector
- getElementsByClassName()
is added in HTML5
- node.classList
provides a way to easily manipulate class names
add
remove
toggle
contains
- Focus management
document.activeElements
contains a pointer to the DOM element that currently has focus.focus()
document.hasFocus()
- Custom Data data-
access by node.dataset.appId
- Markup insertion
.innerHTML
it is not available for all elements. Be extremely careful when using this method..outerHTML
.insertAdjacentHTML()
When using the methods above, it is best to manually remove all event handlers and properties that are on elements.
- node.innerText
- scrollIntoView()
- node.children
contains element
node
- parentNode.contains(childNode)
HTMLCollection()
The HTMLCollection
interface represents a generic collection (array-like object similar to arguments
) of elements (in document order) and offers methods and properties for selecting from the list.
HTMLCollection.length
HTMLCollection.item()
- Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
Image()
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.beginPath();
ctx.moveTo(30, 96);
ctx.lineTo(70, 66);
ctx.lineTo(103, 76);
ctx.lineTo(170, 15);
ctx.stroke();
};
img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
}
See result in here
FormData
var formElement = document.querySelector('form');
var formData = new FormData(formElement);
formData.append('username', 'Zoe');
EventSource
MDN - EventSource
// create a EventSource object
var evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );
// listen to a message
evtSource.onmessage = function(e) {
var newElement = document.createElement("li");
newElement.innerHTML = "message: " + e.data;
eventList.appendChild(newElement);
}
Event
Event dispatch and DOM event flow - W3
- capture phase
- target phase
- bubble phase
Event objects complete these phases as described below. A phase will be skipped if it is not supported, or if the event object’s propagation has been stopped. For example, if the bubbles
attribute is set to false
, the bubble phase will be skipped, and if stopPropagation()
has been called prior to the dispatch, all phases will be skipped.
Event.target
: element that triggers the event
Event.currentTarget
: element where the event is originally binded to.
Event.eventPhase
Event.NONE
Event.CAPTURING_PHASE
Event.AT_TARGET
Event.BUBBLING_PHASE
Event order
http://www.quirksmode.org/js/events_order.html#link4