A DOM introduction
D (document): A Web page document that can be understood to be loaded for the entire web;
O (object): Can be understood as something like a Window object, you can call properties and methods, here is the document object;
M (model): a tree structure that can be understood as a Web document;
1. Node
When loading an HTML page, the Web browser generates a tree structure that represents the internal structure of the page;
DOM constructs this node structure as composed of nodes;
The HTML element is the root node; the head element is the child of the HTML; the meta element is a sibling to the title element;
2. Node type: element node/text node/attribute node
<div title= "element Properties" > Test div</div>
ELEMENT nodes = div;
Attribute node = = title= "Element Properties"
Text node = Test div Two Find element
It provides a convenient and simple method and properties for locating nodes, so that we can operate the nodes quickly.
The DOM (Document Object model) is an API (application interface) for HTML and XML documents.
The DOM depicts a hierarchical tree of nodes where a developer can add/remove and modify portions of a page;
Element Node Lookup method
Method description
getElementById () Gets the node for the specific ID element;
getElementsByTagName () Gets a list of nodes of the same element;
Getelementsbyname () Gets a list of nodes of the same name;
GetAttribute () Gets the value of a specific element node property;
SetAttribute () Sets the value of a specific element node property;
RemoveAttribute () removes specific element node attributes;
1.getElementById ()
Method receives a parameter: Gets the ID of the element;
Returns the Htmldivelement object of the element if the corresponding element is found, or null if it does not exist;
document.getElementById (' box '); [Object Htmldivelement];
When we get to a specific element node through getElementById (), the node object is acquired by us;
And through this node object, we can access a series of its properties;
(1). Accessing the attributes of an element node
Property Description
TagName gets the label name of the element node;
InnerHTML gets the content of the element node, the nonstandard DOM specification;
document.getElementById (' box '). TagName; =>div;
document.getElementById (' box '). InnerHTML; = Test Div;
(2). Accessing HTML Common Properties
Property Description
The ID name of the ID element node;
The title attribute value of the title element node;
Style CSS inline styling property value;
ClassName the class of CSS elements;
document.getElementById (' box '). ID; =>id;
document.getElementById (' box '). title; Get title;
document.getElementById (' box '). style; Gets the Cssstyledeclaration object;
document.getElementById (' box '). Style.color; Gets the value of the color in the style object, which is the style value set within the element row;
document.getElementById (' box '). style.color= ' Red '; Sets the value of color in the style object;
document.getElementById (' box '). ClassName; Get class;
document.getElementById (' box '). Classname= ' pox '; Set class;
document.getElementById (' box '). BBB; Gets the value of the custom attribute, not IE not supported;
2.getElementsByTagName ()
The Htmlcollection method returns an array of object arrays (NodeList), which holds a list of all nodes of the same element name;
document.getElementsByTagName (' * '); Get all the elements with wildcards;
Ps:ie when using wildcards, the canonical declaration of the document's initial HTML is treated as the first element node;
document.getElementsByTagName (' Li '); =>[object Htmlcollection]; get all the LI elements;
document.getElementsByTagName (' Li '). [0]; Gets the first LI element;
3.getElementsByName ()
Gets the element that is set by the same name (name), returning an array of objects htmlcollection (NodeList);
Document.getelementsbyname (' Add '); Gets a collection of input elements with name= ' add ';
PS: For a property that is not HTML-valid, there will be differences in the compatibility of JS acquisition;
IE supports a valid name attribute, but there is an incompatibility problem with a custom property;
4.getAttribute ()
Method gets the value of an attribute in the element;
But it has a certain difference from the method of using ". attr" to get the value of the property directly.
document.getElementById (' box '). getattribute (' mydiv '); Gets the custom attribute value;
document.getElementById (' box '). Mydiv; Gets the custom attribute value, IE support only;
5.setAttribute ()
method sets an attribute and value in the element, and receives two parameters: the property name and value;
If the property itself already exists, then it will be overwritten;
document.getElementById (' box '). SetAttribute (' Align ', ' center '); setting properties and values;
PS: In IE7 and below, using the SetAttribute () method to set the class and style properties has no effect;
6.removeAttribute ()
method to remove HTML attributes;
document.getElementById (' box '). RemoveAttribute (' style '); Remove the style style property;
Three DOM nodes
1.node Node Properties
Nodes can be divided into: element node/attribute node and text node;
These nodes have three properties: Nodename/nodetype and NodeValue;
Information Node Properties
Node type NodeName nodeType nodevalue
element element name 1 null
Property Property Name 2 property value
Text #text 3 Text content
document.getElementById (' box '). NodeType; =>1; element node;
2. Hierarchy Node Properties
Hierarchical nodes can be divided into: parent node and child node/sibling node;
When we get one of the element nodes, we can use the Hierarchy node property to get the node of its related level;
Node relationships
Hierarchy Node Properties
Property Description
ChildNodes reads all child nodes of the current element node;
FirstChild reads the first child node of the current element node;
LastChild gets the last child node of the current element node;
Ownerdocument gets the document root node of the node, which is equivalent to documents;
ParentNode Gets the parent node of the current node;
PreviousSibling gets the previous sibling node of the current node;
NextSibling gets the next sibling node of the current node;
Attributes gets the collection of all the attribute nodes for the current element node;
(1). ChildNodes Properties
Property gets all the child nodes of an element node that contain element nodes and text nodes;
PS: When using Childnodes[n] to return the child node object, it is possible to return the element child node, for example: HtmlElement;
It is also possible to return a text sub-node, for example: text;
Element subnodes can get tag names using nodename or tagname, whereas text subnodes can be obtained using NodeValue;
var box = document.getElementById (' box ');
for (var i=0; i<box.childnodes.length; i++) {
The judgment is the element node, the output element tag name;
if (Box.childnodes[i].nodetype = = = 1) {
Console.log (' element node: ' +box.childnodes[i].nodename);
The judgment is the text node, the output text content;
}else if (Box.childnodes[i].nodetype ===3) {
Console.log (' text node: ' +box.childnodes[i].nodevalue);
}
}
PS1: It is not possible to use the innerHTML property to output text content when acquiring a text node (with the emphasis on not being an element node);
This non-standard attribute must be acquired at the time of the element node in order to output the text contained within;
alert (box.innerhtml); The first difference between innerHTML and nodevalue;
Ps2:innerhtml and NodeValue in the assignment, NodeValue will be contained in the text of the HTML escaped into a special character, so as to achieve the effect of the formation of plain text;
And innerHTML will parse the special characters in the text;
Box.childnodes[0].nodevalue = ' <strong>abc</strong> '; =><strong>abc</strong>;
box.innerhtml = ' <strong>abc</strong> '; =>ABC (style bold);
(2). FirstChild and LastChild Properties
FirstChild = Childnodes[0]; Gets the first child node of the current element;
LastChild = Childnodes[box.childnodes.length-1]; Gets the last child node of the current element;
(3). Ownerdocument Properties
Returns the Document object root node of the node, the object returned is equivalent to documents;
Alert (box.ownerdocument = = = document); =>true; root node;
(4). Parentnode/previoussibling/nextsibling Properties
ParentNode: Returns the parent node of the node;
PreviousSibling: Returns the previous sibling node of the node;
NextSibling: Returns the next sibling node of the node;
alert (box.parentNode.nodeName); Gets the label name of the parent node;
alert (box.firstChild.nextSibling); Gets the second node;
alert (box.lastChild.previousSibling); Gets the second-to-last node;
(5). Attributes Properties
property returns a collection of attribute nodes for the node;
Alert (document.getElementById (' box '). attributes); =>namednodemap;
(6). Ignore blank text nodes
123456789101112131415161718192021222324252627282930313233343536 |
var body = document.getElementsByTagName(
‘body‘
)[0];
// 获取body元素节点;
alert(body.childNodes.length);
// 非IE=7; IE=3;
// PS:在非IE中,标准的DOM具有识别空白文本节点的功能,而IE自动忽略了;
function filterSpaceNode1(nodes){
// 新数组;
var ret = [];
for
(
var i=0; i<nodes.length; i++){
// 如果识别到空白文本节点,就不添加到数组;
if
(nodes[i].nodeType ===3 && /^\s+$/.test(nodes[i].nodeValue))
continue
;
// 把每次的元素节点,添加到数组里;
ret.push(nodes[i]);
}
return ret;
}
// PS:上面的方法,采用忽略空白文件节点的方法,把得到的元素节点累加到数组里返回;
function filterSpaceNode2(nodes){
for
(
var i=0; i<nodes.length; i++){
if
(nodes[i].nodeType ===3 && /^\s+$/.test(nodes[i].nodeValue)){
// 得到空白节点之后,一道父节点上,删除子节点;
nodes[i].parentNode.removeChild(nodes[i]);
}
}
return nodes;
}
// PS:firstChild等方法在获取节点时遇到空白节点,处理方法;
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 nodes/copy nodes/INSERT nodes/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 () Appends the new node to the end of the list of child nodes;
createTextNode () creates a file node;
InsertBefore () Inserts the new node in front;
ReplaceChild () replaces the new node with the old node;
CloneNode () copy node;
RemoveChild () Remove nodes;
(1). Write () method
The write () method can insert any string into the document;
document.write (' <p> This is a paragraph!</p> '); After parsing the 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 list of child nodes of a node;
var box = document.getElementById (' box ');
var p = document.createelement (' P '); Create a new element node <p>;
Box.appendchild (P); Put the new element node <p> Add the end of the child node;
(4). createTextNode () method
This method creates a text node;
var text = document.createTextNode (' paragraph ');
P.appendchild (text); Adds a text node to the end of a child node;
(5). InsertBefore () method
12345678910111213141516 |
// 该方法可以把节点添加到指定节点的前面;
box.parentNode.insertBefore(p,box);
// 在<div>之前添加一个<p>;
box.insertBefore(newNode,
null
);
// 将newNode添加到box自列表的最后节点;
//PS:insertBefore()方法可以给当前元素的前面创建一个节点,但没有提供给当前元素的后面创建一个节点;
function insertAfter(newElement,targetElement){
// 得到父节点;
var parent = targetElement.parentNode;
// 如果最后一个子节点是当前元素,那么直接添加即可;
if
(parent.lastChild === targetElement){
parent.appendChild(newElement);
}
else
{
// 否则,在当前节点的下一个节点之前添加;达成在当前节点后面添加节点的需求;
parentNode.insertBefore(newElement,targetElement.nextSibling);
}
}
|
(6). ReplaceChild () method
The method can replace the node with the specified node;
Box.parentNode.replaceChild (P,box); Replace <div> with <p>;
(7). CloneNode () method
The method can be copied to the node, and the copy of the node returned after the copy belongs to the document, but does not specify a parent node for it;
The parameter is true: Deep copy is performed, which is the copy node and its entire child node tree;
The parameter is false: Performs a shallow copy, copying only the node itself;
var box = document.getElementById (' box ');
var clone = Box.firstChild.cloneNode (true); Gets the first child node, which is true for copying content;
Box.appendchild (clone); Add to the end of the list of child nodes;
(8). RemoveChild () method
The method deletes the specified node;
Box.parentNode.removeChild (box);
JavaScript Document Object Model model DOM