1. Node level
-
A Documen node is the root of each document
-
A document element is the outermost element of a document, one for each document value, and in HTML, always an < HTML > element
-
Element nodes represent HTML elements, attribute nodes represent attributes, document type nodes represent document types, and comment nodes represent accommodations.
1. Node type
-
So Node types inherit from Node types, sharing basic properties and methods.
-
Each node has a nodeType attribute that represents the nodeType
Node type constant Value + description Node.ELEMENT_NODE 1 Element node Node.ATTRIBUTE_NODE 2 Attribute Node Node.TEXT_NODE 3 Text Node Node.CDATA_SECTION_NODE 4 cdata node Node.ENTITY_REFERENCE_NODE 5 The entity references the node Node.ENTITY_NODE 6 Physical Node Node.PROCESSING_INSTRUCTION_NODE 7 Process instruction nodes Node.COMMENT_NODE 8 Comment Node Node.DOCUMENT_NODE 9 Document Nodes Node.DOCUMENT_TYPE_NODE 10 Document type node Node.DOCUMENT_FRAGMENT_NODE 11 Document fragment node Node.NOTATION_NODE 12 symbol node if(someNode.nodeType == Node.ELEMENT_NODE) { // ... } Copy the code
1. NodeName and nodeValue
-
Holds information about the node, the value of which depends on the node type.
if(someNode.nodeType == Node.ELEMENT_NODE) { // somenode. nodeName specifies the label name // somenode. nodeValue is always null } Copy the code
- For the element nodeName representing the label name, nodeValue is always null
2. Node relationship
-
The childrenNodes property, which contains the NodeList instance
NodeList
Is a class array that stores ordered nodes that can be accessed by location.NodeList
Is not an Array instance, but can be accessed with brackets, as welllength
attributeNodeList
Is a DOM structure query, and DOM structure changes are automatically reflected
let firstChild = someNodes.childrenNodes[0] let secondChild = someNodes.childrenNodes.item(1) let count = someNodes.childrenNodes.length Copy the code
-
The parentNode property points to the parent element in the DOM tree
-
Each node in childrenNodes is a sibling of another node in the same list.
previousSibing
The last brothernextSibing
Next brother
-
The firstChild of the parent, firstChild, and the last, lastChild
-
HasChildNodes () method to detect whether there is a child node, equivalent to someNode..childnodes. Length > = 1
-
OwnerDocument only wants Pointers to document nodes that represent the entire document
3. Manipulate nodes
appendChild()
- Add nodes at the end of the childNodes list to return the newly added node.
- If it is an existing node in the document, it is moved from the previous location to the new location
- If the first child is passed, it becomes the last child
insertBefore()
- Add a node at a specific location in the childNodes list and return the newly added node.
- Two parameters: the node to insert and the reference node
- Equivalent if the reference node is null
appendChild()
- Becomes the previous sibling of the reference node
replaceChild()
- Replace nodes, delete known nodes, return nodes to be replaced
- Two parameters: the node to insert and the node to replace
removeChild()
- Removing a node, not replacing it, returns the removed node
- Parameter: Node to be removed
4. Other methods
cloneNode()
Returns the exact same node as the one on which it was called.- Parameter Boolean, indicating whether to deeply copy (copy nodes and their entire DOM tree)
- JavaScript properties added to DOM nodes, such as event handlers, are not copied. Copy only HTML attributes, and optionally copy child nodes.
normalize()
Process the text nodes in the document subtree, delete or merge the text nodes of the empty text or the sibling relationship between text nodes.
2. Document type (9)
- The type of document node, which is an instance of HTMLDocument, representing the entire HTML page
- NodeType: 9
- NodeName: # document
- NodeValue: null
- ParentNode: null
- OwnerDocument: null
- The child node can be of type DocumentType(at most one), Element(at most one), ProcessingInstructoin, or Comment
1. Document child nodes
documentElement
Always point to<html>
The elementbody
Point directly to<body>
The elementdoctype
access<! doctype>
The label
2. Document information
title
contains<title>
The text in the element, displayed in a browser window or title bar, is readable and writableURL
The full URL of the current pagedomain
The domain name of the page,- The value must be the value contained in the original domain
- We can only relax but not tighten
- Changing to the same domain can be used to nest pane communication
referrer
The URL of the page that links to the current page
3. Location elements
-
getElementById()
- Pass id, return if found, return null if not found
-
getElementByTagName()
-
Pass in the tag name, return NodeList, and return an HTMLCollection object in the HTML document
-
HTMLCollection
namedItem()
Retrieves a reference through the name attribute- Obtained by brackets
<img src="xxx" name="myImage"> // images.namedItem("myImage") // images["myImage"] Copy the code
-
Gets all elements passed in *
-
-
getElementsByName()
- Returns all elements with the given name attribute
4. Special sets
document.anchors
Contains all documents with the name attribute<a>
The elementdocument.forms
Include All documents<form>
The elementdocument.images
Include All documents<img>
The elementdocument.links
Contains all of the documents with the href attribute<a>
The element
5. DOM compatibility detection
document.implementation
6. Document writing
- Write (), writeln(), open(), close()
3. Element type
- Represents an XML or HTML element, exposing the ability to access the element’s tag name, child nodes, and attributes
- NodeType: 1.
- NodeName: the label name of the element
- NodeValue: null
- ParentNode: Document or Element object
- You can get the tagName by nodeName or tagName (HTML all caps, actual XML size)
1. HTML elements
- All HTML elements are represented by the HTMLElement type, including both their direct and indirect instances
- HTMLElement directly inherits Element and adds some attributes
- Id: The unique identifier of the element in the document
- Title: Contains additional information about an element, usually in the form of a prompt bar
- Lang: Language code for element content
- Dir: language writing direction
- ClassName: Corresponds to the class attribute, specifying the CSS class of the element
2. Get attributes
getAttribute()
- The property name passed in should be the same as the actual property name
- There is no return NULL
- Can get values for custom attributes that are not formally defined in HTML languages.
- Attribute names are case insensitive
- Custom attributes should be used
data-
Prefix for easy verification - All attributes can be obtained through the corresponding DOM element object’s attributes.
- The attributes of the DOM element object include the five directly mapped attributes and all recognized (non-custom) attributes.
- Properties accessed through DOM objects and
getAttribute()
Attribute differences obtained- Style property
getAttribute()
Return CSS string- The property accessed by a DOM object is a (CSSStyleDeclaration) object
- Events (such as onclick)
getAttribute()
Returns the source code as a string- The DOM object accesses a property that is a JavaScript function
- Style property
3. Set properties
setAttribute()
- Two parameters, the name and value of the property to be set.
- If the attribute name already exists, it is replaced.
- Applies to HTML attributes as well as custom attributes
- The set property name is normalized to lowercase.
- You can also set the value of the element’s attribute by assigning to the DOM object’s attribute directly.
- Adding a custom attribute to a DOM object does not automatically make it an element attribute.
removeAttribute()
- Delete the value of an attribute, removing the entire attribute from the element entirely.
4
attributes
Properties contain an instance of NameedNodeMap, each of which is represented as an Attr node.getNamedItem(name)
Returns the node with the nodeName attribute equal to nameremoveNameedItem(name)
Delete the node whose nodeName attribute is namesetNamedItem(node)
Adds a node node to the list indexed by its nodeName- Item (pos) returns the node at the index position pos.
attributes
The nodeName of each node in the property is the name of the corresponding property, and the nodeValue is the value of the property.- The most useful scenario is when you need to iterate over all the attributes on an element.
5. Create elements
document.createElement()
Creating a new element- Accepts a parameter, the label name of the element to be created.
- You can add attributes to it after you create it
- Once created, it needs to be added to the document using the Add method.
6. Descendants of elements
-
The childNodes property contains all childNodes of the element, including other elements, text nodes, comments, or processing instructions.
-
Check the nodeType of a node (or use children) before performing an operation.
for(let i = 0, len = element.childNodes.length; i < len; i++) { if(element.childNodes[i].nodeType === 1) {... }}Copy the code
4. Text type
- The Text node is represented by the Text type and contains either literal plain Text or an escaped HTML string.
- NodeType: 3
- NodeName: # text
- NodeValue: text saved by a node
- ParentNode: Element object
- Child nodes are not supported
- The Text contained in the Text node can be accessed either through the nodeValue property or through the data property.
appendData(text)
Add text to the end of the nodedeleteDate(offset, count)
Remove count characters from position offsetinsertData(offset, text)
Insert text at offsetreplaceData(offset, count, text)
Replace the text of offset to offset+count with textsplitText(offset)
Split the text node into two text nodes at position offsetsubstringData(offset, count)
Extract the text from position offset to offset+countlength
Property gets the number of characters contained in this node. Equal to nodevalue. length and data.length
- By default, each element can have at most one text node.
- When modifying the contents of a text node, greater-than, less-than, or quotation marks are escaped
Create a text node
document.createTextNode()
Create a new text node- Receives a parameter, the text to insert the node.
- Once created, it needs to be added to the document using the Add method.
2. Normalize text nodes
normalize()
3. Split text nodes
splitText()
5. Comment type
- Comments are expressed through the Comment class
- NodeType: 8
- NodeName: # comment
- NodeValue: Indicates the content of the comment
- ParentNode: Document or Element object
- Child nodes are not supported
- The Comment and Text types inherit from the same base class (CharacterData), with the exception of
splitText()
Outside all methods. - The content of the annotation can be obtained via nodeValue or data.
document.createComment()
Creating a comment node
6. CDATASection type
- Specific to XML, inheriting the Text type.
- NodeType: 4
- NodeName: # cdata section
- NodeValue: CDATA block content
- ParentNode: Document or Element object
- Child nodes are not supported
document.createCDataSection()
Incoming node content creation
7. DocumentType Type
- Contains document type (DOCType) information for the document
- NodeType: 10
- NodeName: indicates the name of the document type
- NodeValue: null
- ParentNode: Document
- Child nodes are not supported
- Dynamic creation is not supported and can only be created while parsing the document code.
- Stored in the
document.doctype
In the - Contains three properties: name, entities, and notations
- Name Indicates the name of the document type
- Entities is the NamedNodeMap of the entity described by this document type and is usually empty
- The NamedNodeMap where natations are the representation of this document type description is usually empty
- Stored in the
8. DocumentFragment type
- A “lightweight” document that can contain and manipulate nodes without the added expense of a full document.
- NodeType: 11
- NodeName: # document – fragments
- NodeValue: null
- ParentNode: null
- Document fragments cannot be added directly to a document, but serve as repositories for other nodes to be added to the document.
document.createDocumentFragment()
Creating a document fragment- The document fragment inherits from the Node type the methods that all document types have to perform DOM operations. If a node in a document is added to a document fragment, the node is removed from the document tree and no longer rendered.
- Document fragments can avoid multiple renders and reduce performance costs.
Attr type
-
Element data is represented in the DOM by the Attr type. Is a node that exists in the element attributes attribute
- NodeType: 2
- NodeName: indicates the attribute name
- NodeValue: indicates the attribute value
- ParentNode: null
- Child nodes are not supported in HTML, and XML neutron nodes can be Text or entityReferences
-
Three attributes
- The name attribute name
- The value attribute values
- Specified indicates whether the property uses the default or the specified value
-
Document.createattrubute () creates a new Attr node
let attr = document.createAttribute('align') attr.value = 'left' element.setAttributeNode(attr) Copy the code
-
GetAttributeNode () gets the Attr node
-
None of the above methods are recommended.
2. DOM programming
1. Dynamic scripts
-
Dynamic scripts are scripts that do not exist when the page is initially loaded and are later included through the DOM.
-
There are two ways to add scripts to a web page dynamically via
- Importing external files
function loadScript(url) { let script = document.createElement('script') script.src = url document.body.appendChild(script) } Copy the code
- Insert source code directly
function loadScriptString(code) { let script = docuemnt.createElement('script') script.type = "text/javascript" try { // compatible with Safari3 or less script.appendChild(document.createTextNode(code)) }catch(ex) { // Compatible with older VERSIONS of IE script.text = code } document.body.appendChild(script) } Copy the code
2. Dynamic styles
-
is used to contain CSS external files
function loadStyles(url) { let link = document.createElemt('link') link.rel = 'stylesheet' link.type = 'text/css' link.href = 'url' let head = document.getElementsByTagName('head') [0] head.appendChild(link) } Copy the code
-
function loadStylesString(css) { let style = documnet.createElement('style') style.tyle = 'text/css' try{ style.appendChild(document.createTextNode(css)) }catch(ex) { // Compatible with IE but easy to crash style.stylesheet.cssText = css } let head = document.getElementsByTagName('head') [0] head.appendChild(style) } Copy the code
3. Operation table
-
properties and methods
caption
To point to<caption>
Pointer to the element (if present)tBodies
, including<tbody>
Elements of the HTMLCollectiontFoot
To point to<tfoot>
Element (if present)tHead
To point to<thead>
Element (if present)rows
Contains an HTMLCollection that represents all linescreateTHead()
To create<thead>
Element, placed in a table, returns a referencecreateTFoot()
To create<tfoot>
Element, placed in a table, returns a referencecreateCaption()
To create<caption>
Element, placed in a table, returns a referencedeleteTHead()
, delete the<thead>
The elementdeleteTFoot()
, delete the<tfoot>
The elementdeleteCaption()
, delete the<caption>
The elementdeleteRow(pos)
Deletes the row at the given positioninsertRow(pos)
Inserts a row at a given position in the row collection
-
< tBody > properties and methods
rows
, including<tbody>
HTMLCollection of all lines in the elementdeleteRow(pos)
Deletes the row at the given positioninsertRow(pos)
Inserts a row at a given position in the row collection, and returns a reference to that row
-
properties and methods
cells
, including<tr>
HTMLCollection of all table elements of the elementdeleteCell(pos)
To delete the table element at the given locationinsertCell(pos)
, inserts a table element at a given position in the table element set, and returns a reference to the table element
4. Use NodeList
- Understand NodeList objects and NamedNodeMap and HTMLCollection
- All three collection types are “real-time”, in which changes in document structure are reflected in real time.
- It is best to limit the number of NodeList operations because each query searches the entire document, and it is best to cache the NodeList queries.
3, MutationObserver interface
- Callbacks can be executed asynchronously when the DOM is modified
- You can view an entire document, part of a DOM tree, or an entire element.
- You can observe changes in element attributes, child nodes, text, or any combination of the first three
1. Basic Usage
- Created by passing in the callback function by calling the MutationObserver constructor
1, Observe () method
-
To associate with the DOM, accept two required parameters:
- The DOM node that you want to watch change
- A MutationObserverInit object
-
The MutationObserverInit object is a dictionary of key-value pair configuration options that control what changes are observed.
let observer = new MutationObserver(() = >console.log('<body> attributes changed')) observer.observe(document.body, {attributes: true}) Copy the code
<body>
Changes to any attributes of the element are detected by the MutationObserver instance- The registered callback function is executed asynchronously
2. Callback and MutationRecord
-
Each callback receives an array of MutationRecord instances. This includes information about what has changed and which parts of the DOM have been affected.
-
There can be multiple events that satisfy the observation criteria, and each callback is passed an array of MutationRecord instances that are enqueued in sequence
let observer = new MutationObserver( (mutationRecords) = > console.log(mutationRecords)); observer.observe(document.body, { attributes: true }); document.body.setAttribute('foo'.'bar'); / / / // { // addedNodes: NodeList [], // attributeName: "foo", // attributeNamespace: null, // nextSibling: null, // oldValue: null, // previousSibling: null // removedNodes: NodeList [], // target: body // type: "attributes" / /} // ] document.body.className = 'foo' document.body.className = 'bar' document.body.className = 'baz' // [MutationRecord, MutationRecord, MutationRecord] Copy the code
-
MutationRecord instance property
attribute instructions target The target node affected by the modification type Change type, “Attributes”, “characterData”, or “childList” oldValue Old value that needs to be enabled in MutationObserverInit attributeName For “attributes” type changes, save the modified attribute name attributeNamespace Saves the modified attribute name for the “attributes” type change that uses the namespace addedNodes The childList changes, including the NodeList of the added node removedNodes The childList changes, including the NodeList of the node to be deleted previousSibling Returns the previous sibling of the changed childList Node nextSibling Returns the next sibling of the changed childList Node -
The second instance passed to the callback function is a MutationObserver instance that observes changes.
3. Disconnect () method
- Aborting the execution of the callback prematurely can be called
disconnect()
methods - A synchronous invocation
disconnect()
Not only are callbacks for subsequent events stopped, but callbacks that have been queued for asynchronous execution are discarded
4. Reuse MutationObserver
- Multiple calls
observer()
Method, you can reuse a MutationObserver object to observe multiple different target nodes. disconnect()
The approach is a one-size-fits-all approach that stops looking at all targets
Reuse MutationObserver
- call
disconnect()
Does not end the life of MutationObserver. You can also reuse the observer and associate it with a new target node.
MutatoinObserverInit and observation scope
- MutatoinObserverInit is used to control the scope of viewing the target node.
attribute | instructions |
---|---|
subtree | Whether to observe the target node tree. Default is false |
attributes | Whether to observe property changes of the target node. The default value is false |
attributeFilter | Array of strings that indicate which properties to observe, default all |
attributeOldValue | Whether to record the value of the property before the change. Default: false |
characterData | Is an observation character data modification. Default is false |
characterDataOldValue | Whether to record character data before changes. Default: false |
childList | Whether the target node points the change event. Default is false |
1. Observe attributes
- The MutationObserver can observe the addition, removal, and modification of node attributes.
- You need to set attributes to true in MutatoinObserverInit
- All attributes are observed by default, and you can set the whitelist using attributeFilter
- Save the original attribute and set attributeOldValue
2. Observe character data
- MutationObserver can observe the addition, deletion, and modification of characters in Text nodes (Text, Comment).
- You need to set characterData to true in MutatoinObserverInit
- Save the original character data and set characterDataOldValue
3. Observe the child nodes
- MutationObserver can target the addition and removal of nodes
- You need to set childList to true in MutatoinObserverInit
- Reordering child nodes will report two event changes
4. Observe subtrees
- The default MutationObserver is to observe changes to an element and its children. You can extend the scope to subtrees of this element.
- You need to set subtree to true in MutatoinObserverInit
Asynchronous callbacks and record queues
- Designed for performance, the core is the asynchronous callback and record queue model. Each change is saved in the MutationRecord instance and then added to the record queue.
- This queue is unique to each MutationObserver instance and is an ordered list of all DOM event variations.
1. Record the queue
- Observer registered callbacks are scheduled as microtasks to the task queue only if there are no previously scheduled microtask callbacks, ensuring that the contents of the record queue will not be processed twice by the callback.
- After the callback is executed, the record queue is emptied and the content is discarded.
2. TakeRecords () method
- Calling MutationObserverd
takeRecords()
The MutationRecord method emptens the record queue, fetching and returning all MutationRecord instances in it. - When you want to disconnect from the observation target, you also want to deal with the call
disconnect()
Is used when a MutationRecord instance is in an abandoned record queue.
Performance, memory, and garbage collection
- Compared to the previous
MutaionEvent
There’s been a lot of progress, but there’s still a cost.
1. Reference to MutationObserver
- The reference relationship between a MutationObserver instance and the target is asymmetric and weak. Does not prevent the garbage collector from reclaiming the target node.
- The target node is a strong reference to the MutationObserver, and if the target node is removed from the DOM and then garbage collected, the associated MutationObserver will be garbage collected as well.
2. Reference to MutationRecord
- The MutationRecord instance contains at least one reference to an existing DOM node, or multiple node references if the childList type is changed.
- If you want to save the change record, save the MutationRecord instance, which also saves its reference node. This prevents these nodes from being recycled.
- You can extract the most useful information from each MutationRecord, save it to a new object, and then discard the MutationRecord to free up memory as quickly as possible.