Elevation Chapter 10th DOM

Source: Internet
Author: User

The DOM (Document Object model) is an API (application programming Interface) for HTML and XML documents.

The DOM depicts a hierarchical tree of nodes that allows you to add, remove, and modify portions of a page.

Note: All DOM objects in IE are implemented in the form of COM objects. This means that DOM objects do not conform to the behavior or activity characteristics of native JavaScript objects.

10.1 Node Hierarchy

Dom depicts a structure composed of multi-layer nodes, each node has its own characteristics, data and methods, and other nodes have a relationship, this relationship constitutes a hierarchy, all page markers are represented as a specific node as the root node of the tree structure.

The document node is the root node of each document, the document nodes node, called the document element, which is the outermost element of the document, and all other elements in the document are contained within the document element. Each document can have only one document element.

In an HTML page, the document element is always the

Each segment of the logo can be represented by a node in the tree: HTML element--element node, attribute (attribute)--attribute node, document type--Document type node, comment--note node.

10.1.1 node type

The DOM1 class defines a node interface that will be implemented by all the node types in the Doom. This node interface is implemented as a node type in JS, which can be accessed in all other browsers except IE. All node types in JS inherit from node type, so all node types share the same basic properties and methods.

Each node has a NodeType property that indicates the type of the node. The node type is represented by the following 12 numeric constants defined in the node type, and any node type must be one:

Node.element_node (1);

Node.attribute_node (2);

Node.text_node (3);

Node.cdata_section_node (4);

Node.entity_reference_node (5);

Node.entity_node (6);

Node.processing_instruction_node (7);

Node.comment_node (8);

Node.document_node (9);

Node.document_type_node (10);

Node.document_fragment_node (11);

Node.notation_node (12);

If we want to know if a node is not an element node, we can know by comparing whether its nodetype and node.element_node are equal, but this method will error in IE, because the best way is to use the node's NodeType and the numerical value to compare, This is supported under all browsers.

For an element node, its nodename is always the (uppercase) label name of the element, and the value of NodeValue is always null.

Each node has a ChildNodes property that holds a NodeList object. NodeList is a class array object that holds an ordered set of nodes that can be accessed by location.

The NodeList object is the result of a dynamically executing query based on the DOM structure, so changes to the DOM structure are automatically reflected in the NodeList object.

For class array objects (such as Arguments,nodelist), you can convert them to arrays using the Array.prototype.slice () method.

// not valid        in IE8 and previous versions var arrayofnodes=array.prototype.slice.call (somenode.childnodes,0);

If you want to convert nodelist to an array in all IE, you must manually enumerate all the members. The following code can be run in all browsers:

functionConverttoarray (nodes) {vararray=NULL; Try{Array=array.prototype.slice.call (nodes,0);//for non-IE browsers}Catch(ex) {array=NewArray ();  for(vari=0,len=nodes.length;i<len;i++) {Array.push (nodes[i]); }            }            returnArray; }

Each node has a ParentNode property that points to the parent node in the document tree.

Each node that is contained in the ChildNodes list can access other nodes of the same list by using previoussibling and nextsibling.

The previoussibling of the first node in the ChildNodes list is null, and the last nextsibling in the list is null.

The parent node's firstchild and LastChild point to the first and last nodes in the list, respectively.

The HasChildNodes () method returns True if the node contains one or more child nodes.

The last property that all nodes have is ownerdocument, which points to the document node that represents the entire document. This relationship represents any document that any node property has, and no node can exist in two or more documents at the same time. With this property, Instead of reaching the top through layers in the node hierarchy, we can access the document nodes directly.

AppendChild () Adds a node to the end of the ChildNodes list. The nodes added here will change the structure directly.

Any DOM node cannot exist in multiple locations in the document at the same time, so if you call AppendChild () to a node that already exists, the existing position will change.

InsertBefore (the node to be inserted as the reference node):

Before a node is placed on a node, if the node being referenced is null, it is inserted to the last, and AppendChild () is the same.

ReplaceChild (node to be inserted, node to replace):

The node to be replaced is returned by this method and removed from the document tree, and the inserted node occupies the removed node location.

You can use the RemoveChild () method if you want to remove only the nodes instead of replacing them. It receives a parameter, which is the node to remove. The removed node becomes the return value of the method.

Not all types of nodes have child nodes, and if a node that does not support child nodes calls the method above, it causes an error.

There are two methods for all types of nodes, one is CloneNode () and the other is normalize ().

CloneNode (Boolean): Creates an identical copy with a Boolean value of True when deep copy, that is, the copy node and its entire child node tree, the Boolean value is False when shallow copy, that is, copy only the node itself.

The copy of the node returned after the copy belongs to the document, but does not have a parent node assigned to it, which is a "orphan" without a location.

CloneNode () copies only the structure and does not replicate events. But IE has a bug here that replicates events, so it's a good idea to remove the events before copying them.

The only function of normalize () is to work with text nodes in the document tree, and when this method is called on a node, it is looked up in the descendant nodes, if an empty text node is found, if the adjacent text nodes are found, merge them into a single text node.

10.1.2 Document Type

JavaScript represents documents by document type. In the browser, the paper object is an instance of HTMLDocument (inherited from document type) that represents the entire HTML page.

The Document object is a property of the Window object that can be accessed as a global object.

The document node has the following characteristics:

The NodeType value is 9;

The value of the nodename is "#document";

The value of the nodevalue is null;

The value of the parentnode is null;

The value of the ownerdocument is null;

Its child nodes may be a documenttype (up to one), Element (up to one), processinginstruction, or comment.

The DocumentElement property always points to the

The Document object also has a body property, pointing directly to the <body> element, using Document.body to refer to <body>

All browsers support the Document.documentelement and Document.body properties.

You can refer to <! by Document.doctype Doctype>.

However, browser support for Document.doctype varies greatly.

The title property of the Document object, which contains the text of the <title> element, is displayed on the title bar or tab of the browser window.

The title of the current page can be read or changed by the title property, and is reflected in the browser's title bar. Modifying the value of the Title property does not change the <title> element.

The URL attribute contains the full page Url,domain property containing only the domain name of the page, and the referrer property holds the URL of the page that is linked to the current page.

getElementById (), receives a parameter: The ID of the element to get. The ID must match the ID of the element exactly, including the case.

If more than one element of the page has the same ID value, getElementById () returns only the first occurrence of the element.

Getelementbytagname (), takes a parameter that is to get the label name of the element, and returns a nodelist that contains 0 or more elements. This method returns a Htmlcollection object, which is a "dynamic" collection, an array of classes.

The Htmlcollection object also has a method Nameditem (), which can be used to get the items in the collection through the name attribute of the element.

document.getElementsByTagName ("*") gets all the elements in the document.

Getelementsbyname (), this method returns all elements with the given name attribute.

Document.anchors, containing all <a> elements with the name attribute in the document;

Document.forms, contains all the <form> elements in the document, with the same results as the document.getElementsByTagName ("form");

Document.images, which contains all the elements in the document, is the same as the document.getElementsByTagName ("img") results.

A document.links that contains all the <a> elements in the document with the HREF attribute.

Dom Consistency detection: Because the DOM is divided into multiple levels and also contains multiple parts, it is necessary to detect which part of the DOM is implemented by the browser, and the Document.implementtation property is the object that provides the appropriate information and functionality for this purpose. It specifies a method for Hasfeature (detects the name of the DOM feature, detects the DOM feature version number), and returns True if the browser supports a given name and version of the feature.

The Document object writes the output stream to a Web page in a method: Write (), Writeln (), open (), close ().

The Write () and Writeln () methods accept a string parameter, which is the text to write to the output stream.

Write () is written as-is, and writeln () adds a newline character (\ n) at the end of the string. In the process of loading a page, you can use both methods to add content dynamically to the page.

If you call document.write () after the document is loaded, the output will rewrite the entire page.

10.1.3 element type

Element Node Features:

The NodeType value is 1;

The value of the nodename is the label name of the element;

The value of the nodevalue is null;

The value of the parentnode may be document or element;

Its child nodes may be element,text,comment,processinginstruction,cdatasection or entityreference.

To access the tag name of an element, you can use the NodeName property, or you can use the TagName property, which returns the same value.

In HTML, tag names are always represented in all capitals, whereas in XML, tag names are always consistent with the source code.

Each element has one or more attributes whose purpose is to give additional information about the corresponding element or its contents. There are three main DOM methods for manipulating properties, namely GetAttribute (), SetAttribute (), and RemoveAttribute (). These three methods can be used for any attribute, including those defined in the form of the HtmlElement type attribute.

GetAttribute () also has access to custom attribute values, and the names of attributes are case insensitive.

In development, getattribute () is often not used, but only the properties of the object are used. The GetAttribute () method is used only if the custom attribute value is obtained.

SetAttribute (the attribute name to set, the attribute value to set): If the attribute exists, it is replaced by the existing one, and if it does not exist, it is created and set.

Because all attributes are attributes, assigning values directly to a property sets the value of the attribute.

RemoveAttribute (), this method is used to completely remove the attributes of an element. Calling this method not only clears the value of the attribute, but also removes the attribute entirely from the element. This method is not commonly used.

The Attributes property contains a NamedNodeMap, which is also a "dynamic" collection. Each attribute of an element is represented by a attr node, and each node is stored in a NamedNodeMap object.

The NamedNodeMap object has the following methods:

getNamedItem (name): Returns the node with the NodeName attribute equal to name;

RemoveNamedItem (name): Removes the node with the NodeName attribute equal to name from the list;

SetNamedItem (node): Adds nodes to the list, with the nodename attribute of the node as the index;

Item (POS): Returns the node at the digital POS location.

For the attributes in the attributes object, the order in which the browsers return is different.

The following code shows how to iterate through each of the elements and then make them into a string format name= "value" name= "value".

functionOutputattributes (Element) {varpairs=NewArray (), Attrname, AttrValue, I, Len;  for(vari = 0,len=element.attributes.length;i<len;i++) {Attrname=Element.attributes[i].nodename; AttrValue=Element.attributes[i].nodevalue; if(element.attributes[i].specified) {Pairs.push (Attrname+ = "=\" "+attrvalue+" \ ""); }                            }            returnPairs.join (""); }

The Document.createelement () method creates a new element, but the new element is not added to the document tree and can be added to the document tree with AppendChild (), InsertBefore (), ReplaceChild ().

10.1.4 Text Type

Text nodes are represented by the literal type and contain plain text content that can be literally interpreted. Plain text can contain escaped HTML code, but cannot contain HTML code.

The text node has the following characteristics:

The NodeType value is 3;

The value of the nodename is "#text";

The value of the nodevalue is the text that the node contains;

ParentNode is an element;

Child nodes are not supported (not).

The text contained in the text node can be accessed through the NodeValue property or the Data property, which contains the same values. Changes to NodeValue are also reflected through data, and vice versa.

Use the following methods to manipulate the text in a node.

AppendData (text): Adds text to the end of the node.

DeleteData (offset,count): Deletes count characters from the position specified by offset.

InsertData (Offset,text): Inserts text from the position specified by offset.

ReplaceData (Offset,count,text): Replaces text with text from the position specified by offset to offset+count.

Splittext (offset): Divides the current text node into two text nodes from the location specified by offset.

Substringdata (Offset,count): Extracts the text from the position specified by offset to offset+count.

If you use createelement to create an element without adding it to the document, the element is not displayed and is added to the document element using AppendChild.

In general, each element has only one text child node, but if the two text nodes are adjacent sibling nodes, two text nodes are created and added to the elements successively, they will be connected and there will be no spaces between them.

You can use normalize () to synthesize multiple text sub-nodes into a single text child node, and the resulting node's nodevalue equals the value of the NodeValue value of each text node before merging.

Splittext () is the exact opposite of normalize (), which divides a text node into two text nodes, the value of a split position in parentheses, the original text to the split point, and the remaining content of the new text node. This method returns a new text node that is the same as the parentnode of the original node.

10.1.5 Comment Type

The comment node has the following characteristics:

The NodeType value is 8;

The value of the nodename is "#conmment";

The value of the NodeValue is the content of the comment;

ParentNode may be document or element;

Child nodes are not supported (not).

10.1.6 cdatasection Type

The Cdatasection node has the following characteristics:

The NodeType value is 4;

The value of NodeName is "#cdata-section";

The value of NodeValue is the content in CDATA;

ParentNode may be document or element;

Child nodes are not supported (not).

10.1.7 DocumentType Type

The NodeType value is 10;

The value of NodeName is the name of DOCTYPE;

The value of the nodevalue is null;

ParentNode is document;

Child nodes are not supported (not).

10.1.8 DocumentFragment Type

The NodeType value is 11;

The value of NodeName is "#document-fragment";

The value of the nodevalue is null;

ParentNode is null;

The child nodes can be element,processinginstruction,comment,text,cdatasection or EntityReference.

10.1.9 attr Type

The NodeType value is 2;

The value of the nodename is the name of the attribute;

The value of the NodeValue is the value of the attribute;

The value of the parentnode is null;

(no) child nodes are not supported in HTML;

A child node in XML can be either text or EntityReference.

10.2 DOM Manipulation Technology

10.2.1 Dynamic Scripting

A script that does not exist at the time of page load but is dynamically added by modifying the DOM at some point in the future.

<script type= "Text/javascript" src= "Client.js" ></script>
The above statement can be explained by the following statement:
var script=document.createelement (' script ');
Script.type= ' Text/javascript ';
script.src= ' Client.js ';
Document.body.appendChild (script);
IE treats <script> as a special element and does not allow the DOM to access its child nodes.
Can write a function, first try to use the standard DOM text node method, in addition to IE will throw out errors other than the browser support, you can use the Try-catch statement to catch IE throws errors, and then for the special method of IE to set the style.
function loadscriptstring (code) {
var script=document.createelement (' script ');
Script.type= ' Text/javascript ';
try{
Script.appendchild (document.createTextNode (code));
}catch (ex) {
Script.text=code;
}
Document.body.appendChild (script);
}

Calling functions
Loadscriptstring ("function Sayhi () {alert (' Hi ');}");
10.2.2 Dynamic Style
A dynamic style is a style that does not exist when the page is loaded, but is dynamically added to the page after the page is loaded.
Add <link> elements to 
The process of loading external style text is asynchronous, that is, the process of loading styles and executing JavaScript code is not in a fixed order.
10.2.3 Operation Form
10.2.4 using NodeList
You should minimize the number of accesses to nodelist, because each time you access nodelist, you run a document-based query. Therefore, you might consider caching the values obtained from the nodelist.
10.3 Summary
The DOM is an API in the language that is used to access and manipulate HTML and XML documents. The DOM1 class visually sees HTML and XML documents as a hierarchical tree of nodes that can be manipulated using JavaScript to alter the appearance and structure of the underlying document.
The DOM is composed of a variety of nodes, briefly summarized as follows:
The most basic node type is nodes, which is used to represent a separate part of the document in an abstract manner, and all other types inherit from node.
The document type represents the entire documentation and is the root node of a set of hierarchical nodes. In JavaScript, the Document object is an instance of document. With the Document object, there are many ways to query and get nodes.
The element node represents all the HTML and XML elements in the document and can be used to manipulate the contents and attributes of those elements.
Dom operations are often the most expensive part of a JavaScript program, with the greatest number of problems caused by access to nodelist. NodeList objects are "dynamic", which means that each time the NodeList object is accessed, a query is run. In view of this, the best way is to reduce DOM operations.

Elevation Chapter 10th DOM

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.