Summary of basic knowledge about javascript DOM operations

Source: Internet
Author: User
Tags javascript array

DOM to add elements and use node attributes
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml xmlns = "http://www.w3.org/1999/xhtml"> <pead> <meta content = "text/ html; charset = gb2312 "http-equiv =" Content-Type "/> <title> Add an element to the DOM, use node attributes </title> </pead> <body> <ul id = "list"> <li> Item 1 </li> </ul> <input type =" button "onclick =" addItem (); "value =" Add item "/> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
I. DOM Basics
1. node level
Document-the top-level node. All other nodes are attached to it.
DocumentType -- DTD reference (use <! DOCTYPE> syntax). It cannot contain subnodes.
DocumentFragment -- other nodes can be saved like a Document.
Element -- indicates the content between the start tag and the end tag, for example, <tag> </tab> or <tag/>. This is the only node type that can contain both features and subnodes.
Attr -- represents a pair of feature names and feature values. This node type cannot contain subnodes.
Text indicates the plain Text contained in the XML document between the start tag and the end tag, or in the CDataSection. This node type cannot contain subnodes.
CDataSection -- <! [CDATA []> Object Representation. This node type can only contain Text nodes as subnodes.
Entity -- represents an Entity definition in the DTD, for example, <! ENTITY foo "foo">. This node type cannot contain subnodes.
EntityReference -- represents an entity reference, for example ". This node type cannot contain subnodes.
ProcessingInstruction -- represents a PI. This node type cannot contain subnodes.
Comment -- represents XML comments. This node cannot contain subnodes.
Notation -- represents the mark defined in the DTD. This is rarely used.

The Node interface defines the features and methods of all Node types.

Features/methods Type/return type Description
NodeName String The node name. It is defined based on the node type.
NodeValue String Value of a node. It is defined based on the node type.
NodeType Number Node type constant value
OwnerDocument Document Document pointing to the node
FirstChild Node Point to the first node in the childNodes list
LastChild Node Point to the last node in the childNodes list
ChildNodes NodeList List of all child nodes
Previussibling Node Indicates a forward sibling node. If this node is the first sibling node, the value is null.
NextSibling Node Point to the next sibling node. If this node is the last sibling node, the value is null.
HasChildNodes () Boolean Returns true if childNodes contains one or more nodes.
Attributes NamedNodeMap Contains Attr objects that represent the characteristics of an Element. It is only used for Element nodes.
AppendChild (node) Node Add node to the end of childNodes
RemoveChild (node) Node Delete a node from childNodes
ReplaceChild (newnode, oldnode) Node Replace oldnode in childNodes with newnode
InsertBefore (newnode, refnode) Node Insert newnodd before refnode in childNodes

In addition to nodes, DOM also defines helper objects that can be used with nodes, but are not part of the DOM document.
NodeList-node array, which is indexed by numerical value. It is used to represent a subnode with an element.
NamedNodeMap-a node table that uses both values and names for indexing. It is used to represent element features.

2. Access related nodes
In the following sections, consider the following HTML page
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> DOM Example </title>
</Head>
<Body>
<P> Hello World! </P>
<P> isn' t this exciting? </P>
<P> You're learning to use the DOM! </P>
</Body>
</Html>

To access the Var oHtml = document.doc umentElement;
Now the variable oHtml contains an HTMLElement object that represents Var oHead = oHtml. firstChild;
Var oBody = oHtml. lastChild;
You can also use the childNodes feature to do the same job. You only need to treat it as a common javascript array and mark it with square brackets:
Var oHead = oHtml. childNodes [0];
Var oBody = oHtml. childNodes [1];
Note that the square brackets mark is actually a simple implementation of NodeList in javascript. In fact, the method for obtaining subnodes from the childNodes list is to use the item () method:
Var oHead = oHtml. childNodes. item (0 );
Var oBody = oHtml. childNodes. item (1 );
The html dom page defines document. body as a pointer to the <body/> element.
Var oBody = ducument. body;
With the three variables oHtml, oHead, and oBody, you can try to determine the relationship between them:
Alert (oHead. parentNode = oHtml );
Alert (oBody. parentNode = oHtml );
Alert (oBody. previussibling = oHead );
Alert (bHead. nextSibling = oBody );
Alert (oHead. ownerDocument = document );
All of the above are outputs "true ".

3. Processing Features
As mentioned above, even if the Node interface already has the attributes method and has been inherited by all types of nodes, however, only
Only Element nodes can have features. The attributes attribute of the Element node is actually NameNodeMap, which provides some methods for accessing and processing its content:
GetNamedItem (name) -- return the node whose nodename attribute value is equal to name;
RemoveNamedItem (name) -- delete a node whose nodename attribute value is equal to name;
SetNamedItem (node) -- add a node to the list and index it according to its nodeName attribute;
Item (pos) -- returns the pos node at the position like NodeList;
Note: All of these methods return an Attr node instead of a specific value.

The NamedNodeMap object also has a length attribute to indicate the number of nodes it contains.
When NamedNodeMap is used to represent a feature, each node is an Attr node. The nodeName attribute is set as the feature name, And the nodeValue attribute is set as the feature value. For example, suppose there is such an element:
<P style = "color: red" id = "p1"> Hello world! </P>
In addition, assume that the variable oP contains a reference pointing to this element. You can access the value of the id feature as follows:
Var sId = oP. attributes. getNamedItem ("id"). nodeValue;
Of course, you can also use numeric values to access the id feature, but this is slightly less intuitive:
Var sId = oP. attributes. item (1). nodeValue;
You can also change the id feature by assigning a new value to the nodeValue attribute:
OP. attributes. getNamedItem ("id"). nodeValue = "newId ";
The Attr Node also has a value attribute that is completely equivalent to (and fully synchronized with) the nodeValue attribute, and the name attribute and nodeName attribute are synchronized. We can use these attributes to modify or change features at will.
Because this method is cumbersome, DOM defines three element methods to help access features:
GetAttribute (name) -- equal to attributes. getNamedItem (name). value;
SetAttribute (name, newvalue) -- equal to attribute. getNamedItem (name). value = newvalue;
RemoveAttribute (name) -- equal to attribute. removeNamedItem (name ).

4. Access a specified Node
(1) GetElementsByTagName ()
The core (XML) DOM defines the getElementsByTagName () method, which is used to return the NodeList of an element whose tagName (Tag Name) attribute is equal to a specified value. In the Element object, the tagName feature is always the name followed by a smaller sign. For example, the tagName of is "img ". The following code returns a list Of all elements in the document:
Var oImgs = document. getElementsByTagName ("img ");
After saving all the images in oImgs, you only need to use square brackets or the Item () method (getElementsByTagName () to return a NodeList with the same name as childNodes ), you can access these nodes one by one as you access the subnodes:
Alert (oImgs [0]. tagName); // outputs "IMG"
If you only want to obtain all the images in the first section of a page, you can call getElementsByTagName () for the first section element, as shown in the following code:
Var oPs = document. getElementByTagName ("p ");
Var oImgsInp = oPs [0]. getElementByTagName ("img ");
You can use an asterisk to obtain all elements in the document:
Var oAllElements = document. getElementsByTagName ("*");
When the parameter is an asterisk, IE6.0 does not return all elements. You must use document. all to replace it.
(2) GetElementsByName ()
The html dom defines getElementsByName (), which is used to obtain all elements whose name attribute is equal to the specified value.
(3) GetElementById ()
This is the second method defined by html dom. It returns the element whose id attribute is equal to the specified value. In HTML, the id feature is unique-this means that no two elements can share the same id. Undoubtedly, this is the fastest way to get a single specified element from the document tree.
Note: If the given ID matches the name attribute of an element, IE6.0 returns this element. This is a bug and must be very careful.

5. Create a New Node
The most common methods are:
CreateDocumentFragment () -- create a File Fragment Node
CreateElement (tagname) -- create an element named tagname
CreateTextNode (text) -- create a text node that contains text

CreateElement (), createTextNode (), appendChild ()
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> createElement () Example </title>
<Script type = "text/javascript">
Function createMessage (){
Var oP = document. createElement ("p ");
Var oText = document. createTextNode ("Hello World! ");
OP. appendChild (oText );
Document. body. appendChild (oP );
}
</Script>
</Head>
<Body onload = "createMessage ()">
</Body>
</Html>

RemoveChild (), replaceChild (), insertBefore ()
Delete a node
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> removeChild () Example </title>
<Script type = "text/javascript">
Function removeMessage (){
Var oP = document. body. getElementsByTagName ("p") [0];
OP. parentNode. removeChild (oP );
}
</Script>
</Head>
<Body onload = "removeMessage ()">
<P> Hello World! </P>
</Body>
</Html>

Replace
<Html>
<Head>
<Title> replaceChild () Example </title>
<Script type = "text/javascript">
Function replaceMessage (){
Var oNewP = document. createElement ("p ");
Var oText = document. createTextNode ("Hello Universe! ");
ONewP. appendChild (oText );
Var oOldP = document. body. getElementsByTagName ("p") [0];
OOldP. parentNode. replaceChild (oNewP, oOldP );
}
</Script>
</Head>
<Body onload = "replaceMessage ()">
<P> Hello World! </P>
</Body>
</Html
Add a new message to the old message
<Html>
<Head>
<Title> insertBefore () Example </title>
<Script type = "text/javascript">
Function insertMessage (){
Var oNewP = document. createElement ("p ");
Var oText = document. createTextNode ("Hello Universe! ");
ONewP. appendChild (oText );
Var oOldP = document. getElementsByTagName ("p") [0];
Document. body. insertBefore (oNewP, oOldP );
}
</Script>
</Head>
<Body onload = "insertMessage ()">
<P> Hello World! </P>
</Body>
</Html>

CreateDocumentFragment ()
Once a node is added to document. body (or its descendant node), the page updates and reflects this change. This is good for a small number of updates. However, when you want to add a large amount of data to the document, it may be very slow to add these changes one by one. To solve this problem, you can create a File Fragment, attach all the new nodes to it, and add the content of the file fragment to the document at one time. If you want to create ten new paragraphs
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> insertBefore () Example </title>
<Script type = "text/javascript">
Function addMessages (){
Var arrText = ["first", "second", "third", "fourth", "th", "sixth", "seventh", "eighth", "ninth ", "tenth"];
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 );
}
</Script>
</Head>
<Body onload = "addMessages ()">
</Body>
</Html>

6. Make the features the same as the properties
In most cases, all the features contained in the html dom element can be used as attributes.
Suppose there are image elements:

If you want to use the core DOM to obtain and set the src and border features, use the getAttribute () and setAttribute () methods:
Alert (oImg. getAttribute ("src "));
Alert (oImg. getAttribute ("border "));
OImg. setAttribute ("src", "mypicture2.jpg ");
OImg. setAttribute ("border", 1 );
However, with html dom, you can use attributes with the same name to get and set these values:
Alert (oImg. src );
Alert (oImg. border );
OImg. src = "mypicture2.jpg ";
OImg. border = "1 ";
The unique feature name and attribute name are different. The class attribute is used to specify a CSS class applied to an element. Because class is a reserved word in ECMAScript, in javascript, it cannot be used as a variable name, attribute name, or function name. Therefore, the corresponding attribute name becomes className;
Note: IE has a big problem in setAttribute (). It is best to use attributes whenever possible.

7. table Method
To help you create a table, html dom adds some features and methods to <table/>, <tbody/>, <tr/>, and other elements.
The following content is added to the <table/> element:

Features/methods Description
Caption Point to the <caption/> element and put it into the table
TBodies <Tbody/> set of elements
TFoot Point to the <tfoot/> element (if any)
THead Point to the <thead/> element (if any)
Rows Set of all rows in the table
CreateTHead () Create the <thead/> element and add it to the table
CreateTFood () Create a <tfoot/> element and put it into a table
CreateCpation () Create a <caption/> element and put it into a table
DeleteTHead () Delete the <thead/> element
DeleteTFood () Delete <tfoot/> element
DeleteCaption () Delete <caption/> Elements
DeleteRow (position) Deletes a row at a specified position.
InsertRow (position) Insert a new row at a specified position in the rows set

<Tbody/> the following content is added to the element:
Features/methods Description
Rows Set of all rows in <tbody/>
DeleteRow (position) Deletes a row at a specified position.
InsertRow (position) Insert a new row at a specified position in the rows set

<Tr/> the following content is added to the element:
Features/methods Description
Cells <Tr/> set of all cells in the element
DeleteCell (postion) Delete a cell at a given position
InsertCell (postion) Insert a new cell at the given position of the cells set.

8. traverse the DOM
NodeIterator, TreeWalker
DOM Level2 functions, which are available only in Mozilla and Konqueror/Safari.
Below are some articles about DOM operations.
Dynamic deletion of multiple TABLE rows using javascript DOM operations
Add events to JavaScript 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.