JavaScript DOM Basics
DOM (Document Object Model) is the Document Object Model. APIs for HTML and XML documents (application interfaces );
DOM depicts a hierarchical node tree where running developers can add, remove, and modify a part of the page;
1. DOM Introduction
D (document): it can be understood as the webpage document loaded on the whole Web;
O (object): it can be understood as something similar to a window object. It can call attributes and Methods. Here we talk about the document object;
M (model): can be understood as the tree structure of webpage documents;
1. Nodes
When an HTML page is loaded, the Web browser generates a tree structure to indicate the internal structure of the page;
DOM understands this node structure as a node;
The html element is the root node, the head element is the child node of html, and the meta element and the title element are sibling;
2. node type: Element Node/text node/attribute node
<Div title = "element property"> test Div </div>
Element Node => div;
Property node => title = "element property"
Text node => test Div 2 search Element
W3C provides easy and simple methods and attributes for locating nodes, so that we can quickly perform operations on nodes;
DOM (Document Object Model) is the Document Object Model. APIs for HTML and XML documents (application interfaces );
DOM depicts a hierarchical node tree where running developers can add, remove, and modify a part of the page;
Element Node Search Method
Method description
GetElementById (): the node that obtains the specific ID element;
GetElementsByTagName () obtains the node list of the same element;
GetElementsByName () obtains the list of nodes with the same name;
GetAttribute () gets the attribute value of a specific element node;
SetAttribute () sets the attribute value of a specific element node;
RemoveAttribute () removes node attributes of a specific element;
1. getElementById ()
// Method receives a parameter: Get the element ID;
// If an element is found, the HTMLDivElement object of the element is returned. If the element does not exist, null is returned;
Document. getElementById ('box'); // [object HTMLDivElement];
// When we get a specific element node through getElementById (), this Node object is obtained by us;
// With this Node object, we can access a series of its attributes;
(1) accessing the attributes of element nodes
Attribute description
TagName: obtains the label name of an element node;
InnerHTML obtains the content in the element node, which is not W3C DOM specification;
Document. getElementById ('box'). tagName; // => DIV;
Document. getElementById ('box'). innerHTML; // => test Div;
(2) accessing common HTML attributes
Attribute description
Id of the node;
The title attribute value of the title element node;
Style CSS inline style attribute values;
Class of the className CSS element;
Document. getElementById ('box'). id; // => id;
Document. getElementById ('box'). title; // obtain the title;
Document. getElementById ('box'). style; // obtain the CSSStyleDeclaration object;
Document. getElementById ('box'). style. color; // gets the color value of the style object, that is, the style value set in the element row;
Document. getElementById ('box'). style. color = 'red'; // set the color value in the style object;
Document. getElementById ('box'). className; // get class;
Document. getElementById ('box'). className = 'pox'; // set the class;
Document. getElementById ('box'). bbb; // gets the value of the custom attribute, which is not supported by IE;
2. getElementsByTagName ()
// Return an object array HTMLCollection (NodeList), which stores the list of all nodes with the same element name;
Document. getElementsByTagName ('*'); // use wildcards to obtain all elements;
// PS: when using wildcards, IE regards the standard declaration of html at the beginning of the document as the first element node;
Document. getElementsByTagName ('lil'); // => [object HTMLCollection]; get all li elements;
Document. getElementsByTagName ('lil'). [0]; // obtain the first li element;
3. getElementsByName ()
Gets the element set with the same name, and returns an object array HTMLCollection (NodeList );
Document. getElementsByName ('add'); // gets the set of input elements with name = 'add;
// PS: For attributes that are not valid in HTML, there will also be differences in the compatibility obtained by JS;
// IE supports valid name attributes, but there may be incompatibility issues with custom attributes;
4. getAttribute ()
Method to obtain a property value of an element;
However, it is different from the method that uses ". attr" to obtain the attribute value;
Document. getElementById ('box'). getAttribute ('mydiv '); // get the custom property value;
Document. getElementById ('box'). mydiv; // get custom attribute values, only supported by IE;
5. setAttribute ()
The method sets an attribute and value in the element, and receives two parameters: attribute name and value;
If the attribute already exists, it will overwrite it;
Document. getElementById ('box'). setAttribute ('align ', 'center'); // you can specify attributes and values;
// PS: In IE7 and earlier, using the setAttribute () method to set the class and style attributes has no effect;
6. removeAttribute ()
You can remove HTML attributes;
Document. getElementById ('box'). removeAttribute ('style'); // remove the style attribute;
Three DOM nodes
1. node attributes
// Nodes can be divided into element nodes, attribute nodes, and text nodes;
// These nodes have three attributes: nodeName/nodeType and nodeValue;
Information node attributes
Node Type nodeName nodeType nodeValue
Element element name 1 null
Attribute attribute name 2 Attribute Value
Text # text 3 text Content
Document. getElementById ('box'). nodeType; // => 1; Element Node;
2. Hierarchical node attributes
// Hierarchical nodes can be divided into Parent nodes and child nodes/sibling nodes;
// When we obtain one of the element nodes, we can use the hierarchical node attribute to obtain the nodes of the corresponding layers;
Node relationship
Hierarchical node attributes
Attribute description
ChildNodes reads all the subnodes of the current element node;
FirstChild reads the first subnode of the current element node;
LastChild obtains the last subnode of the current element node;
OwnerDocument obtains the document root node of the node, which is equivalent to document;
ParentNode obtains the parent node of the current node;
Previussibling obtains the previous same-level node of the current node;
NextSibling obtains the next peer node of the current node;
Attributes obtains the set of all attribute nodes of the current element node;
(1). childNodes attributes
Obtain all the subnodes of an element node. These subnodes include the element node and the text node;
PS: When childNodes [n] is used to return the subnode object, it is possible that the returned element subnode, such as HTMLElement;
It may also return Text subnode, such as Text;
The element subnode can use nodeName or tagName to obtain the tag name, while the text subnode can use nodeValue to obtain the tag name;
Var box = document. getElementById ('box ');
For (var I = 0; I <box. childNodes. length; I ++ ){
Identify as an element node and name of the output element tag;
If (box. childNodes [I]. nodeType = 1 ){
Console. log ('element node: '+ box. childNodes [I]. nodeName );
Determines whether the node is a text node and outputs the text content;
} Else if (box. childNodes [I]. nodeType = 3 ){
Console. log ('text node: '+ box. childNodes [I]. nodeValue );
}
}
PS1: The innerHTML attribute cannot be used to output text content when a text node is obtained (not an element node;
This non-standard attribute can output the text contained in the element node only when it is obtained;
Alert (box. innerHTML); the first difference between innerHTML and nodeValue;
PS2: when the values of innerHTML and nodeValue are assigned, nodeValue converts the HTML contained in the text into special characters to form the plain text;
InnerHTML parses special characters in the text;
Box. childNodes [0]. nodeValue = '<strong> abc </strong>'; => <strong> abc </strong>;
Box. innerHTML = '<strong> abc </strong>'; => abc (bold style );
(2). firstChild and lastChild attributes
FirstChild = childNodes [0]; get the first subnode of the current element;
LastChild = childNodes [box. childNodes. length-1]; get the last subnode of the current element;
(3). ownerDocument attributes
Returns the document Object root node of the node. The returned object is equivalent to document;
Alert (box. ownerDocument === document); // => true; root node;
(4). parentNode/previussibling/nextSibling attributes
ParentNode: returns the parent node of the node;
Previussibling: returns the previous same-level node of the node;
NextSibling: returns the last peer node of the node;
Alert (box. parentNode. nodeName); // obtain the label name of the parent node;
Alert (box. firstChild. nextSibling); // obtain the second node;
Alert (box. lastChild. previussibling); // obtain the second to last node;
(5). attributes
Attribute returns the set of attribute nodes of the node;
Alert (document. getElementById ('box'). attributes); // => NamedNodeMap;
(6) Ignore blank text nodes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
Var body = document. getElementsByTagName ('body') [0]; // get the body Element Node; Alert (body. childNodes. length); // non-IE = 7; IE = 3; // PS: in non-IE, standard DOM can recognize blank text nodes, While IE automatically ignores them; Function filterSpaceNode1 (nodes ){ // New array; Var ret = []; For (var I = 0; I <nodes. length; I ++ ){ // If it is recognized as a blank text node, It is not added to an array; If (nodes [I]. nodeType ==3 &/^ \ s + $/. test (nodes [I]. nodeValue) continue; // Add each element node to the array; Ret. push (nodes [I]); } Return ret; } // PS: in the preceding method, ignore the blank file node to accumulate the element nodes and return them to the array; Function filterSpaceNode2 (nodes ){ For (var I = 0; I <nodes. length; I ++ ){ If (nodes [I]. nodeType = 3 &/^ \ s + $/. test (nodes [I]. nodeValue )){ // After a blank node is obtained, the child node is deleted from the parent node; Nodes [I]. parentNode. removeChild (nodes [I]); } } Return nodes; } // PS: methods such as firstChild encounter blank nodes when obtaining the node; Function removeWhileNode (nodes ){ For (var I = 0; I <nodes. childNodes. length; I ++ ){ If (nodes. childNodes [I]. nodeType = 3 &/^ \ s + $/. test (nodes. childNodes [I]. nodeValue )){ Nodes. childNodes [I]. parentNode. removeChild (nodes. childNodes [I]); } } Return nodes; } |
Four-node operation
// DOM can not only find nodes, but also create/copy nodes/insert/delete nodes and replace nodes
Node Operation Method
Method description
Write () This method can insert any string into the document;
CreateElement () creates an element node;
AppendChild (): append a new node to the end of the subnode list;
CreateTextNode () creates a file node;
InsertBefore () inserts a new node in front;
ReplaceChild () replaces the old node with the new node;
CloneNode () replication node;
RemoveChild () removes a node;
(1). write () method
// The write () method can insert any string into the document;
Document. write ('<p> This is a paragraph! </P> '); // The parsed text;
(2). createElement () method
The createElement () method can create an element node;
Document. createElement ('P'); // [object HTMLParagraphElement];
(3). appendChild () method
The appendChild () method adds a new node to the end of the subnode list of a node;
Var box = document. getElementById ('box ');
Var p = document. createElement ('P'); // create a new element node <p>;
Box. appendChild (p); // Add the new element node <p> to the end of the subnode;
(4). createTextNode () method
This method creates a text node;
Var text = document. createTextNode ('Paragraph ');
P. appendChild (text); // Add the text node to the end of the subnode;
(5). insertBefore () method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// This method can be used to add a node to the front of a specified node; Box. parentNode. insertBefore (p, box); // Add a <p> before <div>; Box. insertBefore (newNode, null); // Add newNode to the last node of the box self-list; // PS: The insertBefore () method can create a node before the current element, but it is not provided to the end of the current element to create a node; Function insertAfter (newElement, targetElement ){ // Obtain the parent node; Var parent = targetElement. parentNode; // If the last subnode is the current element, add it directly; If (parent. lastChild === targetElement ){ Parent. appendChild (newElement ); } Else { // Otherwise, add the node before the next node of the current node to meet the requirement of adding the node after the current node; ParentNode. insertBefore (newElement, targetElement. nextSibling ); } } |
(6). replaceChild () method
This method can replace a node with a specified node;
Box. parentNode. replaceChild (p, box); // replace <div> with <p>;
(7). cloneNode () method
// This method can copy the child node. The Node copy returned after the copy belongs to the document, but the parent node is not specified for it;
// If the parameter is true, deep replication is performed, that is, copying the node and its entire subnode tree;
// If the parameter is set to false, perform a shortest copy and only copy the node itself;
Var box = document. getElementById ('box ');
Var clone = box. firstChild. cloneNode (true); // obtain the first subnode. true indicates copying content;
Box. appendChild (clone); // Add it to the end of the subnode list;
(8) removeChild () method
This method deletes a specified node;
Box. parentNode. removeChild (box );