Javascript Document Object Model (DOM) instance analysis

Source: Internet
Author: User
Tags processing instruction

Basic knowledge Review:

DOM (Document Object Model) is a Document Object Model. DOM actually treats HTML as an XML file and looks at HTML from an Object's perspective, it can be said that DOM is the most useful invention of Web following HTML.

 

Some review of XML webpage

When SGML is used to define the DTD of HTML, it is found that HTML itself is not standardized. The main reason is that some labels can be omitted/not included/Not Allowed To End tags (</xxx>), labels are embedded with each other but not normalized, and the attribute value definition methods are not uniform. Therefore, XML appears, and the non-standard parts of HTML are clearly defined. Note that XML defines the syntax and norms of a language, it is a general term for a series of languages that meet this specification. In different cases, different specific implementations define different labels and attributes to solve different problems, such as RDF, RSS, SOAP, XSLT, XSL and so on. Of course, html xml is implemented as XHTML. The essence of XML is to use structured plain text to express data.

 

XML syntax points:

The first behavior is XML prolog, which is generally <? Xml version = "1.0"?>, This row tells the xml praser/browser how the XML is prase. Webpage tutorial Network

The document type declaration (DTD) is followed, for example, <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Webpage tutorial Network

Next is the document element, which must include all other labels. Is the outermost tag of the XML. That is, the Root Element. Note that this should be consistent with the root element type declared in the DTD, as shown in the preceding html.

Do not want to be used by Praser to parse things <! [CDATA []>.

Use of <? ... ?> The enclosed statement is called PI (processing instruction). It serves to give praser more specific information.


Xml api:

Webjx. Com

SAX (Sample API for XML): the first, implemented in Java, event-based, and praser parses the XML document from top to bottom. When each tag/attribute/value... It will trigger the event, and the specific definition of what the event is done by the programmer.
Advantages: lightweight, fast, disadvantages. When you want to stop, roll back, or specify a specific part of the document, you have to start from the first line of the document.

Webjx. Com

DOM: Based on the tree structure. After parsing, you do not need to re-Parse any document objects you want to access or modify. DOM is not targeted at languages, and the browser is responsible for Javascript support for DOM implementation. Webjx. Com

----------------------------------------- Webjx. Com

Core of DOM: Node


Because DOM is a tree structure, a Node is abstracted as an object Node, which is the core object of DOM.

There are 12 types of nodes, which are determined by the value of Node. nodeType (1-12:

Primary Node. ELEMENT_NODE (1)


❑ Node. ATTRIBUTE_NODE (2)


Worker Node. TEXT_NODE (3): <! [CDATA []> contains plain text. It has no subnodes.

Worker Node. CDATA_SECTION_NODE (4): The child Node must be TextNode.

Webpage tutorial Network


Worker Node. ENTITY_REFERENCE_NODE (5 ):

 

Define Node. ENTITY_NODE (6): object definition in DTD <! ENTITY foo "foo">, no subnode

Worker Node. PROCESSING_INSTRUCTION_NODE (7): PI, no subnode

Webjx. Com


Worker Node. COMMENT_NODE (8)

 

Primary Node. DOCUMENT_NODE (9): the Root element of the outermost layer, including all other nodes.

Webjx. Com


Required Node. DOCUMENT_TYPE_NODE (10): DTD, <! DOCTYPE ......>


Worker Node. DOCUMENT_FRAGMENT_NODE (11)

Webpage tutorial Network

Worker Node. NOTATION_NODE (12): Nation definition in DTD

Webpage tutorial Network

Node attributes and Methods webpage tutorial

NodeName returns String. The name of ths node; this is defined depending on theype of node.
NodeValue returns String. The value of the node 'this is defined depending on the type of node.
NodeType Returns Number. One of the node type constant values.
OwnerDocument returns Document. Pointer to the document that this node belongs.
FirstChild returns Node. Pointer to the first node in the childNodes list.
LastChild returns Node. Pointer to the last node in the childNodes list.
ChildNodes returns NodeList. A list of all child nodes.
Previussibling returns Node. Pointer to the previous sibling; null if this is the first sibling.
NextSibling returns Node. Pointer to the next sibling; null if this is the last sibling.
Attributes returns NamedNodeMap. Contains Attr objects respresenting an element's attributes; only used for Element nodes.
AppendChild (node) returns Node. Adds node to the end of childNodes.
HasChildNodes () Returns Boolean. Returns true when childNodes contains one or more nodes.
RemoveChild (node) returns Node. Removes node from childNodes.

Webjx. Com

ReplaceChild (newnode, oldnode) returns Node. Replace oldnode in childNodes with newnode.
InsertBefore (newnode, refnode) returns Node. Inserts newnode before refnode in childNodes.

-----------------------------------------

DOM usage


DOM is hierarchical. Different browsers have different levels of DOM support. DOM level1 (core, used to parse XML-base documents, and dom html, used for HTML, Because DOM is not only for HTML), DOM Level2 (event, in the past, DHTML was used to support styles, communicate with CSS, and so on ..) DOM level3 (DOM Load and Save; DOM Validation; Support for XML1.0, including: XML Infoset, XPath, XML Base)

 

Netscape Navigator 1.0-4.x DOM compatibility (-)
Netscape 6.0 + (Mozilla 0.6.0 +) DOM compatibility (Level 1, Level 2, Level 3 (partial ))
Internet Explorer 2.0-4.x DOM compatibility (-)
Internet Explorer 5.0 DOM compatibility (Level 1 (minimal ))
Internet Explorer 5.5 + DOM compatibility (Level 1 (almost all ))
Opera 1.0-6.0 DOM compatibility (-)
Opera 7.0 + DOM compatibility (Level 1 (almost all), Level 2 (partial ))
Safari 1.0 +/Konqueror ~ 2.0 + DOM compatibility (Level 1) Webjx. Com

Get Node:


/* Use the document Object */
Var oHtml = document.doc umentElement; webpage tutorial Network

/* Get Var oHead = oHtml. firstChild;
Var oBody = oHtml. lastChild;

Webpage tutorial Network


/* This method can be used */
Var oHead = oHtml. childNodes [0];
Var oBody = oHtml. childNodes [1];

/* You can also use the method to obtain the index value of the array */
Var oHead = oHtml. childNodes. item (0 );
Var oBody = oHtml. childNodes. item (1 );

 

/* Use document. body to get <body/> */
Var oBody = document. body;

Use the Node butes value: the Attributes () method of the Node interface to return a NamedNodeMap. You can obtain and operate the specific Attribute from it. Or you can use the getAttribute () method of the Node interface to directly obtain the Attribute.

Webjx. Com


/* Use the Node attribute's getNamedItem () method */
Var sId = oP. attributes. getNamedItem ("id"). nodeValue;


/* Or use the item () method */
Var sId = oP. attributes. item (1). nodeValue;


/* Or directly use Node's getAttribute () to obtain the Id */
Var sId = oP. getAttribute ("id ");

 

Get the specified Node: Use getElementsByTagName ()

Webjx. Com

/* Obtain Elements */
Var oImgs = document. getElementsByTagName ("img ");

/* Obtain all */
Var oPs = document. getElementsByTagName ("p ");
Var oImgsInP = oPs [0]. getElementsByTagName ("img ");

GetElementsByName (), getElementsById ();

/* Obtain the <div> */
Var oDivs = document. getElementsByTagName ("div ");
Var oDiv1 = null;
For (var I = 0; I <oDivs. length; I ++ ){
If (oDivs [I]. getAttribute ("id") = "div1 "){
ODiv1 = oDivs [I]; break;
}
}

Webpage tutorial Network

/* Use document. getElementById ()*/
Var oDiv1 = document. getElementById ("div1 ");

Generate and operate nodes


CreateAttribute (name): Create an attribute node named name. Supported by IE, Mozilla, and opera, not Safari.
CreateCDATASection (text): Create a CDATA zone with the subnode text. Mozilla, IE, Opera, and Safari are not supported.
CreateComment (text): Creates a comment node whose comment content is text. All browsers support this feature.
CreateDocumentFragment (): Creates a fragment node. All browsers support this feature.
CreateElement (tagName): creates an element node named tagName. All browsers support this feature.
CreateEntityReference (name): Creates an entity reference node with the given name. Mozilla support. IE, Opera, and Safari are not supported.
CreateProcessingInstruction (target, data): Creates a PI node with the given target and data. Mozilla support. IE, Opera, and Safari are not supported.
CreateTextNode (text): Creates a text node that contains text. All browsers support this feature. Webjx. Com

The most common method is createElement (), createDocumentFragment (), and create TextNode ().

/* Use createElement (), createTextNode (), and appendChild () to dynamically add nodes */
Function createMessage (){
Var op = document. createElement ("p ");
Var oText = document. createTextNode ("hello world! ");
Op. appendChild (oText );
Document. body. appendChild (op );
}

 

Using removeChild (), replaceChild (), and insertBefore ()

/* Remove node */
Function removeMessage (){
Var op = document. body. getElementsByTagName ('P') [0];
Op. parentNode. removeChild (op );
} Webpage teaching network

/* Replace node */
Function insertMessage (){
Var oNewP = document. createElement ('P ');
Var oText = document. createTextNode ('Hello csser! ');
ONewP. appendChild (oText );
Var oOldP = document. getElementsByTagName ('P') [0];
Document. body. insertBefore (oNewP, oOldP );
}

Webpage tutorial Network

 

Use createDocumentFragment ()

Webjx. Com


/* Common practice */
Var arrText = ['first', 'second', 'third'];
For (var I = 0; I <arrText. length; I ++ ){
Var op = document. createElement ('P ');
Var oText = document. createTextNode (arrText [I]);
Op. appendChild (oText );
Document. body. appendChild (op );
}

Webpage tutorial Network

/* Use documentFragment */
Var arrText = ['first', 'second', 'third'];
Var oFragment = document. createDocumentFragment ();
For (var I = 0; I <arrText. length; I ++ ){
Var op = document. createElement ('P ');
Var oText = document. createTextNode (arrText [I]);
Op. appendChild (oText );
OFragment. appendChild (op );
}
Document. body. appendChild (oFragment );

Webjx. Com


CSSER Note: The comparison above shows that the DocumentFragment method can improve efficiency. Webpage tutorial Network

-----------------------------------------

Html dom:

Webpage tutorial Network


The core method of using DOM is for all XML, and there are special methods for html dom, such

Use DOM core: oImg. setAttribute ("src", using mypicture2.jpg ");


Use html dom: oImg. src = export mypicture2.jpg ".

-----------------------------------------

Webpage tutorial Network

DOM traversal and parentNode (), firstChild (), lastChild (), nextSibling (), previousSibling () (brother)

 

Http://www.csser.com/html/csser/webstandards/200703/04/1034.html

 

Related Article

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.