##1.Common Properties of DOM Nodes (Supported by All Nodes)##
-
nodeType: Element 1, Attribute 2, Text 3
-
nodeName: Uppercase form of the element tag name
-
nodeValue: null for element nodes, text content for text nodes, attribute value for attribute nodes
-
Relationship properties: parentNode, childNodes, nextSibling, previousSibling, firstChild, lastChild
-
ownerDocument: Document node (document object)
##2.Operating DOM Nodes (Add/Delete/Modify)##
-
appendChild(node); Adds a node to the end of the current node's childNodes list. If node already exists, moves node under the current node
-
insertBefore(node, targetNode); Inserts node before targetNode
-
replaceChild(node, targetNode); Replaces targetNode with node. Note: After replacement, targetNode is not destroyed, it just becomes a document fragment outside the DOM tree
-
removeChild(node); Removes node. Note: After removal, node is not destroyed either. This method returns a reference to node
-
cloneNode(true/false); Copies a node exactly the same as the current node. If true, deep copy; otherwise shallow copy. IE copies related event handlers, other browsers do not
-
normalize(); Used to delete empty text nodes and merge adjacent text nodes
##3.Related to document Object##
-
document.documentElement; Points to the element
-
document.body; Points to the element
-
document.title; Points to the element. Direct assignment can modify the document title
-
document.URL; Gets the complete URL
document.domain; Gets the domain name. Can directly assign to set the domain name. When multiple frames in a page need to communicate, this property must be modified to lift cross-origin security restrictions
document.referrer; Gets the URL of the previous page, may be an empty string
-
Finding Elements
-
document.getElementById(str);
-
document.getElementsByTagName(str); Returns a collection, accessed using bracket notation. Inside brackets can be a string to get elements by name attribute value (str can be * to get all DOM elements)
-
document.getElementsByName(str); Mostly used for radio button groups
-
P.S. The first two apply to DOM operations for all XML documents, the last one only applies to HTML documents. As for document.querySelector(str) and document.getElementsByClassName(str) supported by HTML5, they are not discussed here. The 3 methods listed above are fully browser-compatible
-
document.write(str); Document writing. Calling directly during document loading outputs content at the specified position. If placed in a load event handler, it rewrites the entire page
-
document.createTextNode(text); Creates a text node. document.createElement(tagName); Creates an element
##4.Related to Element Nodes##
-
Element node properties: id, title (similar to ToolTip), className, all are readable/writable (these 3 properties are very commonly used when writing native js code, especially className, very convenient)
-
elem.getAttribute(attr); Gets the value of attr attribute, can also get custom attributes. But in HTML5, custom attributes should have a "data-" prefix (of course, it's fine without it, just a specification requirement), accessed via elem.dataset.attr
elem.setAttribute(attr, value); Sets attribute value, only used to set custom attributes because custom attributes cannot be set directly
elem.removeAttribute(attr); Deletes attribute and value ([IE6-] does not support)
P.S. Generally access attributes directly, e.g., elem.id, elem.style, etc. The get/setAttribute methods are not commonly used (only for reading/writing custom attributes), because accessing style and onclick or other event properties via functions returns strings, while direct access returns operable objects (such as function references), so element properties are generally accessed directly
-
attributes property: elem.attributes['id'].nodeValue = value; Can also access attributes this way, but more often attributes property is used to traverse element attributes
-
nodeType detection should be added when traversing element nodes, because some browsers treat whitespace between tags as nodes (Unicode BOM signature)
##5.Text Nodes##
node.nodeValue or node.data can both access text content
##6.DOM Performance Optimization##
- Minimize the number of NodeList accesses
NodeList, NamedNodeMap, HTMLCollection are all live updates. The return value of document.getElementByxxx is of this type. Should minimize NodeList accesses because checking the DOM tree is required during access, causing considerable performance overhead. References to NodeList objects should be saved. For example, avoid code like this:
for(var i = 0;i < 100;i++){
document.getElementsByTagName('li')[i].className = 'disabled';
}
This is terribly inefficient. A better approach is:
var lis = document.getElementsByTagName('li');
for(var i = 0;i < 100;i++){
lis[i].className = 'disabled';
}
Common HTMLCollection objects include: document.forms, document.images, document.links, document.anchors
- Use DocumentFragment to Avoid Multiple "Live Updates"
DocumentFragment is a relatively uncommon but very useful node, especially important in performance optimization. When inserting a large number of DOM nodes, we have two choices: either insert one by one into the DOM tree, or first insert into a document fragment, then insert the fragment into the DOM tree. The first method requires n DOM tree updates, while the second requires only 1 update. For example:
//Create document fragment
var frag = document.createDocumentFragment();
//Insert nodes
var node = null, text = null;
for(var i = 0;i < 10;i++){
node = document.createElement('p');
text = document.createTextNode('Paragraph' + i);
node.appendChild(text);
frag.appendChild(node);
}
//Insert the fragment carrying nodes into the DOM tree
document.body.appendChild(frag);
Document fragments do not exist in the DOM tree. Inserting a fragment into the DOM tree actually inserts the nodes it carries. A document fragment is an invisible container. Of course, you can also create a div as a container, same principle as creating a document fragment. As long as it avoids n live updates, because when any node in the DOM tree updates, the browser re-renders the page, which means a large amount of style value calculations
- Performance Differences of getElementByxxx
Id query is the fastest, TagName is second, ClassName is the slowest. Of course, these differences can generally be ignored, but mobile pages should fully consider this, after all mobile devices don't have the same conditions as PCs. Additionally, saving references to frequently used elements can reduce unnecessary DOM lookups, thereby improving performance.
##7.Dynamically Creating img/script/link Elements##
Given that this part differs from general DOM operations and has more associations with events, it is discussed in detail in JS Learning Notes 6_Events
No comments yet. Be the first to share your thoughts.