JavaScript Document Object Model (DOM) instance analysis

Source: Internet
Author: User
Tags cdata object model processing instruction tagname

Basic Knowledge Review:

Dom is the Document Object model, the DOM is actually processing HTML as an XML file, looking at the HTML with the object's eye, which can be said to be the most useful invention of the web after HTML.

Some Review of XML Web page teaching Network

SGML, a universal specification for tabbed languages, discovers that HTML itself is very irregular when SGML is used to define the HTML DTD. The main performance in some tags can be omitted/no/do not allow the end tag (</xxx>), the tags are embedded with each other and very nonstandard, the definition of property values are not uniform and so on. So XML appears, and the nonstandard place in HTML is clearly defined, note that XML is defined as a language of syntax and norms, is a series of language to meet this standard collectively, specific different occasions will have different specific implementation of the definition of different tags 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 real meaning of XML is to use structured plain text to express data.

XML several Syntax essentials:

The first behavior XML prolog, typically <?xml version= "1.0", tells the XML praser/browser how the XML is prase. Web Teaching Network

Then the document type declaration (DTD), such as <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

Web Teaching Network

Then the document element, which must enclose all the other tags. is the outermost tag of the XML. That is, root element, note that this is consistent with the root element type declared in the DTD, such as the HTML above.

Do not want to be praser resolution of things with <! [cdata[]]> enclosed.

In the middle of document element;? ... ? The > enclosed statement is called PI (processing instruction), which is to give praser some more specific information.


XML API:

Webjx.com

SAX (Sample API for XML): First, Java language implementation, Event-based,praser parsing XML document from top to bottom, when encountering each tag/attribute/value ... , the event is fired, and what is specifically done in the event is defined by the programmer.
Advantages, Lightweight,fast, flaws, any time you want to stop, roll back, or specifically specify that a particular part of the document is parsed, you have to start with the first line of the document to parse from scratch.

Webjx.com

DOM: Based on the tree structure, and when parsing is complete, you do not need to parse the object to access or modify the added document. Dom is not language-oriented, and the browser is responsible for JavaScript support for DOM implementations. Webjx.com

————————————————————————————————————————— webjx.com

The core of DOM: Node


Because the DOM is a tree structure, a node is abstracted as Object node, which is the core object of DOM: Web page Teaching Network

There are 12 kinds of node, which are determined by the value of Node.nodetype (1-12), and are divided into:

❑node.element_node (1)


❑node.attribute_node (2)


❑node.text_node (3): <! [The plain text enclosed in cdata[]]>, he has no child nodes

❑node.cdata_section_node (4): The child node must be Textnode

Web Teaching Network


❑node.entity_reference_node (5):

❑node.entity_node (6): Entity definition in a DTD <! ENTITY foo "foo", No Child nodes

❑node.processing_instruction_node (7): PI, No child nodes

Webjx.com


❑node.comment_node (8)

❑node.document_node (9): Outermost root element, including all other nodes

Webjx.com


❑node.document_type_node (a):D td,<! Doctype...........>


❑node.document_fragment_node (11)

Web Teaching Network

❑node.notation_node (): Nation definition in DTD

Web Teaching Network

Node's properties and methods Web page teaching Network

NodeName returns a string. The name of ths node;this is defined depending on theype of node.
NodeValue returns a string. The value of the node ' is defined depending on the type of node.
NodeType returns number. One of the node type constant values.
Ownerdocument returns to document. Pointer to the document so this node belongs to.
FirstChild returns node. Pointer to the the ChildNodes list.
LastChild returns node. Pointer to the last node in the ChildNodes list.
ChildNodes returns nodelist. A List of all the child nodes.
PreviousSibling returns node. Pointer to the previous sibling;null if it is the "the"
NextSibling returns node. Pointer to the next sibling;null if it's the last sibling.
Attributes returns NAMEDNODEMAP. Contains Attr Objects respresenting A element ' s attributes;only used for element nodes.
AppendChild (node) returns node. Adds node to the end of ChildNodes.
HasChildNodes () returns a 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.

—————————————————————————————————————————

Use of DOM


The DOM is hierarchical, and different browsers have different levels of support for the DOM. Dom Level1 (core, used to parse xml-base documents, and DOM HTML for HTML, because DOM is not just for HTML), Dom Level2 (event, formerly through DHTML Support, style, and CSS communication, Wait a minute.. Dom Level3 (Dom Load and save;dom Validation; XML1.0 support, 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:


* * Through Document Object/
var ohtml = document.documentelement; Web Teaching Network

/* Get var ohead = Ohtml.firstchild;
var obody = Ohtml.lastchild;

Web Teaching Network


* * Can be used in this way
var ohead = ohtml.childnodes[0];
var obody = ohtml.childnodes[1];

/* You can also use the method to get 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;

Using the attributes value: the attributes () method of the node interface returns a NamedNodeMap from which the specific attribute can be obtained and manipulated. or the GetAttribute () method with the node interface itself to get attribute directly.

Webjx.com


/* Use node's attribute of getNamedItem () method * *
var sId = OP.attributes.getNamedItem ("id"). nodevalue;


/* or use the item () method * *
var sId = OP.attributes.item (1). NodeValue;


/* or directly using node's getattribute () to get ID * * *
var sId = Op.getattribute ("id");

Get the specified node: using getElementsByTagName ()

Webjx.com

/* Get elements * *
var Oimgs = document.getelementsbytagname ("img");

/* Get all the * *
var oPs = document.getElementsByTagName ("P");
var oimgsinp = ops[0].getelementsbytagname ("img");

There are also Getelementsbyname (), GetElementsById ();

/* Get ID "div1" <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;
}
}

Web Teaching Network

/* Use document.getElementById () * *
var oDiv1 = document.getElementById ("Div1");

Generating and manipulating node


CreateAttribute (name): Creates a property node named name. Ie,mozilla,opera support, Safari does not support.
Createcdatasection (text): Creates a CDATA area with a child node of text. Mozilla support, Ie,opera,safari not supported.
Createcomment (text): Creates a comment node with the comment content of text. Supported by all browsers.
Createdocumentfragment (): Creates a document fragment (fragment) node. Supported by all browsers.
CreateElement (TagName): Creates an element node named TagName. Supported by all browsers.
Createentityreference (name): Creates a entity reference node with the given name. Mozilla support. Ie,opera,safari not supported.
Createprocessinginstruction (target, data): Creates a PI node with the given target and data. Mozilla support. Ie,opera,safari not supported.
createTextNode (text): Creates a text node that contains text. Supported by all browsers. Webjx.com

The most common and most important method of observation is createelement (), Createdocumentfragment (), create Textnode ().

/* Use createelement (), createTextNode (), appendchild () dynamically add nodes/
function CreateMessage () {
var op = document.createelement ("P");
var otext = document.createTextNode ("Hello world!");
Op.appendchild (Otext);
Document.body.appendChild (OP);
}

Use RemoveChild (), ReplaceChild (), and InsertBefore () Web Teaching Network

/* Remove node */
function Removemessage () {
var op = document.body.getElementsByTagName (' P ') [0];
Op.parentNode.removeChild (OP);
Web 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);
}

Web Teaching Network

Using Createdocumentfragment ()

Webjx.com


/* Common Practice * *
var arrtext = [' A ', ' 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);
}

Web Teaching Network

/* Use DocumentFragment * *
var arrtext = [' A ', ' 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 above comparison can be seen, through the documentfragment way can improve efficiency. Web Teaching Network

—————————————————————————————————————————

HTML DOM:

Web Teaching Network


The core approach to using the DOM is for all XML, and there are special methods for the HTML DOM, such as

Use Dom Core:oImg.setAttribute ("src", "mypicture2.jpg");


Use HTML DOM:OIMG.SRC = "Mypicture2.jpg"; Web Teaching Network

—————————————————————————————————————————

Web Teaching Network

DOM traversal and ParentNode (), FirstChild (), LastChild (), nextSibling (), PreviousSibling () (brothers)

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

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.