Basic Javascript DOM knowledge

Source: Internet
Author: User

/*
Javascript Implementation of dom (basic)
Author: shine
*/
Dom is a Document Object Model that defines methods and attributes for operating XML documents, but it is only a series of interfaces implemented by other languages, such as xerces in Java, javascript ,. net

And so on, although the implementation methods are different, but there is one that will not change, that is, dom api, before officially entering our topic, let's take a look at common Dom APIs.

Solution ):

1. Common Dom APIs (void indicates no return value or no parameter)
1) The domdocument object indicates the document structure of the entire XML file. This object is already built into JavaScript. All other nodes are generated by it.
Attribute:
Name type description
Documentelement indicates the root node of the XML file.
Method:
Parameter description
Createelement (tagname); element string creates an element node
Createtextnode (text); text string to create a text node
Createattribute (name); ATTR string creates an attribute node
Createdocumentfragment (); documentfragment void creates a document clip
Getelementbyid (ID); element string obtains the element according to the element ID attribute.
Getelementsbytagname (tagname); nodelist string obtains the element list based on the element Tag Name
Getelementsbyname (name); nodelist string obtains the element list based on the element name attribute.

2) The main objects in the domnode object Dom, domattriement, domelement, and domtext all inherit from this object.
Attribute:
Name type description
Nodename string node name
Nodevalue string node Value
Nodetype number Node Type
Parentnode node parent node
Nextsibling node: next sibling Node
Previussibling node a sibling Node
Owerdocument document
Childnodes nodelist subnode list
First subnode of firstchild Node
Lastchild node: Last subnode
Attributes namednodemap attribute list

Method:
Parameter description
Removechild (node) void node deletes a subnode
Appendchild (node) void node add subnode

3) The domelement object represents the "Tag Element" in the Dom and inherits from the node. Therefore, attributes and methods in the node can be used. In addition, there are several useful methods.
(Besides the methods and attributes of the Node object, there are also :)
Method:
Parameter description
Setattribute (attrname, value) string, string set attributes
Getattribute (attrname) string to get the attribute
Removeattribute (attrname) void string Delete attribute

4) The domattribute object indicates the element attribute.
(Besides the methods and attributes of the Node object, there are also :)
Attribute:
Name type description
Name string attribute name
Owerelement element
Value string attribute value

5) The domtext object indicates the text node of the element.
(Besides the methods and attributes of the Node object, there are also :)
Attribute
Name type description
Length number the length of the text

6) Dom nodelist node list (one of the auxiliary objects, list structure)
Attribute:
Name type description
Length number the length of the list
Method:
Parameter description
Item (I) node number obtains the specified Node

7) Dom namednodemap node map (Secondary object 2, map structure)
Attribute:
Name type description
Length number the length of the map
Method:
Parameter description
Item (I) ATTR number obtains the specified Node
Getnameditem (name) ATTR string node for obtaining the specified name
Removenameditem (name) void string deletes a node with the specified name

After taking a rough look at domapi, I started to enter the topic:
2. Use DOM:
1) access related nodes:
Exp:
Function Test (){
VaR ohtml = document.doc umentelement;
VaR ohead = ohtml. firstchild;
VaR obody = ohtml. lastchild;
// The second method obtains the body: var obody = ohtml. childnodes [0];
// Method 3: Get the body: var obody = Document. Body

Alert (ohead. parentnode = ohtml );
Alert (obody. parentnode = ohtml );
Alert (ohead. nextsibling = obody );
Alert (obody. previussibling = ohead );
Alert (ohtml. ownerdocument = document );
}

Note:
After writing JavaScript code, add the event to the Body Tag: <body onload = "text ();"> (this is the case in the following example, do not directly write code test in the <SCRIPT> label, because

JavaScript and HTML are interpreted and executed, that is, the execution of one row and one row. If the code is written directly, it is very likely that the labels such as the body have not been generated and are called in Javascript, so it is best to put them in the function.

Function, triggered by onload)

2) check node type:
Function Test (){
// Common node types. Since ie only supports numbers and does not support character constants such as element_node, you can use enumeration for conversion.
VaR node = {
Element_node: 1,
Attribute_node: 2,
Text_node: 3,
Document_node: 9
}

VaR ohtml = document.doc umentelement;
Alert (ohtml. nodetype = node. element_node );
Alert (document. nodetype = node. document_node );
}

3) Processing Features
Element has an attributes attribute, which is of the namednodemap type, so it can use the namednodemap method (dom api has been mentioned)
Add a line to test1.html: <p id = "A1" align = "center"> I LOVE YOU </P>

// JavaScript document
Function Test (){
VaR op = Document. getelementbyid ("A1"); // obtain the element by specifying the ID attribute
// Method 1 for setting the attribute ID and align of the OP Element
// Op. Attributes. getnameditem ("ID"). nodevalue = "A5 ";
// Op. Attributes. getnameditem ("align"). nodevalue = "right ";
// Method 2
Op. setattribute ("ID", "A6 ");
Op. setattribute ("align", "Left ");

// Method 1 for obtaining the op element attribute ID and align
// Var id = op. Attributes. getnameditem ("ID"). nodevalue;
// Var align = op. Attributes. getnameditem ("align"). nodevalue;
// Method 2
VaR id = op. getattribute ("ID ");
VaR align = op. getattribute ("align ");

Alert (ID );
Alert (align );
}

4) access a specified node:
A. getelementsbytagname () returns the Element Set of the specified tag name.
Add the following content to test1.html:
<P id = "A1" align = "center"> I LOVE YOU </P>
<P id = "A2" align = "center"> but you don't know </P>

// JavaScript document
Function Test (){
VaR OP1 = Document. getelementsbytagname ("p ");
Alert (op1.length );
Alert (OP1 [0]. childnodes [0]. nodevalue); // obtain the text in the first <p>
Alert (OP1 [1]. childnodes [0]. nodevalue); // obtain the text in the second <p>
}

B. getelementbyname () returns the Element Set of the attribute of the specified tag name.
(This example completes the "select all" function)
Add the following content to test1.html:
<Form method = "Post">
<Input type = "checkbox" name = "color" value = "red"/> Red <br/>
<Input type = "checkbox" name = "color" value = "green"/> green <br/>
<Input type = "checkbox" name = "color" value = "blue"/> blue <br/>
<Input type = "checkbox" name = "color" value = "all" onclick = "test ();"/> select all
</Form>

// JavaScript document
Function Test (){
VaR allboxes = Document. getelementsbyname ("color"); // obtain all nodes whose name attribute is color.
VaR allselected = allboxes. Item (allboxes. Length-1); // get the last all selected node
// Select all
For (VAR I = 0; I <allboxes. length; I ++ ){
If (allselected. Checked)
Allboxes. Item (I). Checked = true;
Else
Allboxes. Item (I). Checked = false;
}
}

C. getelementbyid () returns the element of the specified tag ID attribute. (If this is used multiple times in the previous example, the example is not used)
Note; bug in IE: Sometimes getelementbyid () is retrieved by name instead of ID. In fact, there is a reason: because HTML is interpreted and executed, that is, one row and one row are executed, in IE

Search for matched elements in a row with the name and ID, for example:
VaR o = getelementbyid ("color1 ")
Alert (O. value );
First case:
<Input type = "checkbox" id = "color1" name = "color" value = "green"/> green <br/>
<Input type = "checkbox" id = "AAA" name = "color1" value = "red"/> Red <br/>
The output is green.

Case 2:
<Input type = "checkbox" id = "color" name = "color1" value = "green"/> green <br/>
<Input type = "checkbox" id = "color1" name = "AAA" value = "red"/> Red <br/>
The output is green.

Case 3:
<Input type = "checkbox" id = "AAA" name = "color1" value = "red"/> Red <br/>
<Input type = "checkbox" id = "color" name = "color1" value = "green"/> green <br/>
Output: red

Case 4:
<Input type = "checkbox" id = "color1" name = "AAA" value = "red"/> Red <br/>
<Input type = "checkbox" id = "color1" name = "color" value = "green"/> green <br/>
Output: red

From the above four cases, we can see that, whether it is the name attribute or the ID attribute, as long as the "interpreted" element has any matching, the element will be returned, and because getelementbyid

Select only one element, so it only selects the First Matching Element (whether name or ID ).

5) create and operate nodes
In this example, the elements in the arrtext array are added to the body.
Method 1:
// JavaScript document
Function Test (){
VaR arrtext = ["one", "two", "three", "four", "five", "Six", "Seven", "eight", "Nine ", "Ten"];
For (VAR I = 0; I <arrtext. length; I ++ ){
VaR element = Document. createelement ("p ");
VaR text = Document. createtextnode (arrtext [I]);
Element. appendchild (text );
Document. Body. appendchild (element );
}
}
If you use method 1, you need to call document. Body. appendchild (element) 10 times, which will refresh the page 10 times. You can use documentfragment.

Method 2:
// JavaScript document
Function Test (){
VaR arrtext = ["one", "two", "three", "four", "five", "Six", "Seven", "eight", "Nine ", "Ten"];
VaR fragment = Document. createdocumentfragment ();
For (VAR I = 0; I <arrtext. length; I ++ ){
VaR element = Document. createelement ("p ");
VaR text = Document. createtextnode (arrtext [I]);
Element. appendchild (text );
Fragment. appendchild (element );
}
Document. Body. appendchild (fragment );
}

3. html Dom features
I have read another article "dom parsing Quick Start (3) -- DOM level2 modules", which is no stranger to HTML Dom. "dom Level 2 HTML (HTML): Extended Dom provides

The HTML document structure is used as an interface for XML processing ." That's right. html Dom is a moduel in Dom level2.
1) make the features the same as the properties
For example:

Follow the previous method to get or set the SRC and border attributes of IMG:
// JavaScript document
Function Test (){
VaR IMG = Document. getelementbyid ("img1 ");
Alert (IMG. getattribute ("src "));
IMG. setattribute ("border", "0 ");
Alert (IMG. getattribute ("border "));
}

Use html dom:
// JavaScript document
Function Test (){
VaR IMG = Document. getelementbyid ("img1 ");
Alert (IMG. SRC );
IMG. Border = 0;
Alert (IMG. Border );
}

Now we should understand what it is called "Let the features be the same as the properties.
Note:
Most feature names are the same as attribute names and have only one special feature: class. It is a class selector in CSS and corresponds to classname, for example:
<Div id = "div1" class = "Header"> </div>

VaR DIV = Document. getelementbyid ("div1 ");
Alert (Div. classname );

2) table method.
The table is also improved in Dom html. The example below is to traverse the table.
Prepare a table
<Table id = "mytable">
<Tr>
<TD> 1 </TD>
<TD> 2 </TD>
</Tr>

<Tr>
<TD> 3 </TD>
<TD> 4 </TD>
</Tr>
</Table>

Traverse table:
// JavaScript document
Function Test (){
VaR table = Document. getelementbyid ("mytable ");
For (VAR I = 0; I <Table. Rows. length; I ++)
For (var j = 0; j <Table. Rows [I]. cells. length; j ++)
Alert (table. Rows [I]. cells [J]. innertext );
}
Note:
Pay attention to two common attributes here:
A. Rows indicates all rows in the table.
B. cells indicates all cells (columns) in the table)
C. If you want to access the J column value of row I: rows [I]. cells [J]

4. Dom traversal. Since IE does not support the relevant Dom level module, I will not talk about it here. However, although Javascript is restricted by browsers, Java can do this function.

See my other article "dom parsing Quick Start (3) -- DOM level2 modules"

5. Test and Dom standard consistency
Use
VaR testdom = Document. Implementation. hasfeature ("XML", "1.0 ")
This method has two parameters: the feature to be checked and the feature version. (For the feature list, see "dom parsing Quick Start (3) -- DOM level2 modules ")

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.