The meaning of the DOM
-
DOM stands for Document Object Model
-
There are three types of objects in JavaScript
Local Object Native Object
Object Function String Number Boolean Error EvalError SyntaxError TypeError RageError ReferenceError URIError Date RegExp Copy the code
Built-in Object Built-in Object
Global: A generic name for a class of objects, which are virtual and represent all methods and properties under the objectisNaN(),parseInt,NumberDecodeURL (), decodeURL(), etcMath,Infinity,NaN,undefinedEtc are local objects with properties under Global. Built-in objects are internal objects of ECMAScriptCopy the code
Host Object Host Object
Objects provided by the environment that executes JS, namely browser objectswindowObject -> BOM. There is no fixed specification between browsersdocumentObject -> DOM, w3c compliantdocument 是 windowThe object under the BOM contains the DOMCopy the code
-
DOM is a set of methods provided by the browser to manipulate HTML and XML documents
Elements and nodes
-
A node contains elements that are part of a node, the element node
-
The node classification
Element node, attribute node, text node, comment node, document node, etc
-
Elements are element objects, including HTMLDivElement, HTMLInputElement and HTMLHtmlElement, which inherit from the constructor HTMLElement. HTMLElement inherits from Node, which is the Node object
-
Document inherited from the constructor HTMLDocument prototype, HTMLDocument inherited from the prototype of document
document.__proto__ -> HTMLDocument.prototype HTMLDocument.prototype.__proto__ -> Document.prototype Copy the code
Access to elements
-
Get the element by ID
document.getElementById(); // Return the corresponding HTMLElement // For getElementById(), IE8 and below are case insensitive and can match names Copy the code
-
Gets a collection of elements by class name
Compatible with Internet Explorer 9 or later
document.getElementsByClassName(); // 返回元素集合 HTMLCollection Copy the code
-
Gets the collection of elements by tag name
document.getElementsByTagName(); // 返回元素集合 HTMLCollection Copy the code
-
Get the element by name
document.getElementsByName(); // 返回元素集合 HTMLCollection // Often used with form elements Copy the code
-
Get an object from a selector
Compatible with IE8 and above, is a new addition to HTML5 Web API
document.querySelector(); // Returns the first Node object selected by the selector, Node document.querySelectorAll(); // Returns the list of nodes selected by the selector NodeList // querySelector, querySelectorAll is lower performance than getElementById, etc Copy the code
The querySelectorAll method returns NodeList, and the getElements series methods return HTMLCollection
The former is static. After the collection is acquired, the content is added or deleted. The collection does not change and does not have real time
HTMLCollection is dynamic and changes with the document operation
Walk through the node tree
-
parentNode
Get the parent node
document.getElementsByTagName("html") [0].parentNode -> document // The parentNode of the HTML tag element is document // The superlative node is document, and the parent of document is null Copy the code
-
childNodes
Gets a collection of child nodes
document.getElementById("box").childNodes // Include element node, text node, comment node etc Copy the code
-
FirstChild, lastChild
Gets the first or last child node
document.getElementById("box").firstChild // First child node document.getElementById("box").lastChild // The second child node Copy the code
-
NextSibling, previousSibling
Gets the previous or next sibling node
document.getElementById("box").nextSibling // Last sibling node document.getElementById("box").previousSibling // Next sibling node Copy the code
-
getAttributeNode()
Get property node
document.getElementById("box").getAttributeNode("id") // Get the attribute node ID Copy the code
Iterate over the element node
-
parentElement
Get the parent element node, compatible with IE9 and above
document.getElementsByTagName("html") [0].parentElement -> null // parentElement of the HTML tag element is null Copy the code
-
children
Gets a collection of child elements. Ie6-8 also contains comment nodes, and IE9 and above only contains element nodes
document.getElementById("box").children // Contains only element nodes document.getElementById("box").chilElementCount // children.length Copy the code
-
FirstElementChild, lastElementChild
Gets the first or last child element node, compatible with IE9 and above
document.getElementById("box").firstElementChild // The first child node document.getElementById("box").lastElementChild // The second child node Copy the code
-
NextElementSibling, previousElementSibling
Gets the next or previous sibling element node, compatible with IE9 and above
document.getElementById("box").nextElementSibling // The last sibling element node document.getElementById("box").previousElementSibling // Next sibling element node Copy the code
Attributes of nodes
-
nodeName
Returns the node name, read-only element node, element name uppercase
document.getElementById("box").nodeName // DIV // Text node -> #text // Comment node -> #comment document.nodeName // #document // document node -> #document Copy the code
-
nodeValue
Returns node content. Read and write attribute nodes, text nodes, comment nodes are available
document.getElementById("box").getAttributeNode('id').nodeValue // box document.getElementById("box").getAttributeNode('id').value // Same effect Copy the code
-
nodeType
Returns the number of the node type, read-only
Element nodes1An attribute node2Text node3Comment node8 document 9 DocumentFragment 11 Copy the code
NodeType encapsulates childNodes to filter out element nodes
function childElementArray(node) { var arr = [], nodes = node.childNodes; for (var i = 0; i < nodes.length; i++) { var item = nodes[i]; if (item.nodeType === 1) { arr.push(item); }}return arr; } Copy the code
-
attibutes
Returns a class array of the attribute nodes of the element node
document.getElementById("box").attributes[0].nodeValue // Get the nodeValue of the first attribute node Copy the code
-
hasChildNodes
Returns a Boolean value for whether there are child nodes
The DOM tree structure
graph TB A(Node) --> B(Document) A --> C(Element) A --> D(CharacterData) A --> E(Attributes) B --> F(HTMLDocument) D --> G(Text) D --> H(Comment) C --> I(HTMLElement) I --> J(HTMLHtmlElement) I --> K(HTMLHeadElement) I --> L(HTMLDivElement) I --> M(HTML... Element)
-
The DOM structure tree shows the inheritance of the constructor and the direction of the prototype chain
-
The Document prototype is inherited by HTMLDocument, as well as XMLDocument
-
The CharacterData archetype is the ancestor of the text node and comment node
-
HTMLElement has a variety of HTML corresponding to the tag… Element, used to construct Element nodes
-
Ways to pay attention to
GetElementById and getElementsByName are only on the prototype of Document, only Document can be used
QuerySelector, querySelectorAll, getElementsByClassName, getElementsByTagName are on the Document and Element prototypes, That is, both document and element node objects can be used
var box = document.getElementById("box"); box.getElementById("list"); / / an error Copy the code
-
Properties to be aware of
Document. bady, Document. head and document.title inherit from the prototype of HTMLDocoment
Document. documentElement inherits from the document prototype
document.bady; // Body tag element document.head; // Head tag element, compatible with IE9 and above document.title; // The text node in the title element document.documentElement; // HTML tag element Copy the code
Node-related operations
-
document.createElement()
Creating element nodes
var div = document.createElement("div"); // Pass in the label name Copy the code
-
document.createTextNode()
Creating a text node
-
document.createComment()
Creating a comment node
-
document.createDocumentFragment()
Performance can be improved by creating a document shard, adding nodes to it, and inserting the document shard into the document
-
appendChild()
Add child nodes at the end of the node and have the clipping node function
var div = document.createElement("div"), text = document.creaetTextNode("Text"); div.appendChild(text); document.body.appendChild(div); Copy the code
-
insertBefore(a, b)
Insert node B before node A inside the node
Element nodes have no insertAfter method and can be encapsulated
Element.prototype.insertAfter = function (target, origin) { var after = origin.nextElementSibling; if (after) { this.insertBefore(target, after); } else this.appendChild(target); } // nextElementSibling compatible with IE9 Copy the code
-
removeChild()
Remove child nodes from the document, but still retain space footprint in memory
-
remove()
Node call, delete itself, can free up memory
-
replaceChild(a, b)
Replace child node B with node A
-
innerHTML
You can take values, you can assign values, and assignments can parse HTML code
-
innerText
You can take values, you can assign values, and the assignments are parsed into text nodes, and label symbols are transcoded into character entities
Older Versions of Firefox do not support textContent, which has the same function
-
The setAttribute (), the getAttribute ()
Sets and gets properties
var div = document.createElement("div"); div.setAttribute('id'.'box'); div.getAttribute('id'); / / return box Copy the code
-
dataset
HTML5 attributes that start with the name data- and can be accessed through the dataset method
Compatible with Internet Explorer 9 or later
// <p data-name="Jett" data-age="22"></p> document.getElementsByTagName("p") [0].dateset // {name: 'Jett', age: '22'} Copy the code