JavaScript DOM Operating Basics Summary _javascript Tips

Source: Internet
Author: User
Tags tagname javascript array
Dom adding elements, using node properties
<! 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>dom add elements, using node properties </title> <script language= " JavaScript "type=" Text/javascript ">//Xiaozu wen geovindu@163.com var nr = 1; function AddItem () {var list = document.getElementById ("list"); var newNode = document.createelement ("Li"); var NewLink = document.createelement ("a"); Newlink.setattribute ("href", "http://www.jb51.net/"); nr++; var newtextnode = document.createTextNode ("Item" + NR); Newlink.appendchild (Newtextnode); Newnode.appendchild (NewLink); List.appendchild (NewNode); } </script></pead> <body> <ul id= "list" ><li>item 1</li></ul> <input type = "button" onclick= "AddItem ();" Value= "Add item"/> </body> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

First, Dom Basics
1. Nodes (node) hierarchy
document--the topmost node, all the other nodes are attached to it.
DOCUMENTTYPE--DTD references (using <! doctype> syntax), which cannot contain child nodes.
documentfragment--can save other nodes like the document.
element--represents the content between the start and end tags, such as <tag></tab> or <tag/>. This is the only node type that can contain both attributes and child nodes.
attr--represents a pair of attribute names and attribute values. This node type cannot contain child nodes.
text--represents the normal text contained within an XML document between the start and end labels, or cdatasection. This node type cannot contain child nodes.
cdatasection--<! The object representation of the [cdata[]]>. This node type can contain only text node text as a child node.
entity--represents an entity definition in a DTD, such as <! ENTITY foo "foo" >. This node type cannot contain child nodes.
entityreference--represents an entity reference, such as ". This node type cannot contain child nodes.
processinginstruction--represents a pi. This node type cannot contain child nodes.
comment--represents an XML annotation. This node cannot contain child nodes.
notation--represents the notation defined in the DTD. This is rarely used.

The node interface defines the attributes and methods that are contained by all nodes types.
Features/methods Type/return type Description
NodeName String The name of the node, defined by the type of the node
NodeValue String The value of the node, defined by the type of the node
NodeType Number One of the type constant values of the node
Ownerdocument Document Point to the document to which this node belongs
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
PreviousSibling Node Point to the previous sibling node; If this node is the first sibling node, then the value is null
NextSibling Node Point to the latter sibling node; If this node is the last sibling node, then the value is null
HasChildNodes () Boolean When childnodes contains one or more nodes, returns true
Attributes NamedNodeMap Contains a Attr object that represents an attribute of an element; only for ELEMENT nodes
AppendChild (node) Node Add node to end of ChildNodes
RemoveChild (node) Node Remove 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, the DOM defines helper objects that can be used with nodes, but are not part of the DOM document.
An array of nodelist--nodes indexed by numeric values, used to represent and child nodes of an element.
namednodemap--a node table that uses both numeric and first names for the element attribute.

2. Access to related nodes
Consider the following HTML page in the following sections
Copy Code code as follows:

<title>dom example</title>
<body>
<p>hello world!</p>
<p>isn ' t this exciting?</p>
<p>you ' re learning to-use the dom!</p>
</body>

To access var ohtml = document.documentelement;
The variable ohtml now contains a HtmlElement object representing var ohead = Ohtml.firstchild;
var obody = Ohtml.lastchild;
You can also use the ChildNodes feature to do the same work. Just use it as a normal JavaScript array, using square brackets to mark:
var ohead = ohtml.childnodes[0];
var obody = ohtml.childnodes[1];
Note that the square bracket tag is actually a simple implementation of nodelist in JavaScript. Actually, the way to get a child node 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 a <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.previoussibling==ohead);
alert (bhead.nextsibling==obody);
alert (ohead.ownerdocument==document);
All of the above outputs "true".

3. Processing characteristics
As mentioned earlier, even if the node interface already has a attributes method and has been inherited by all types of nodes, however, only
ELEMENT nodes can have attributes. The Attributes property of the element node is actually Namenodemap, which provides some ways to access and process its contents:
getNamedItem (name)--Returns the node with the NodeName property value equal to name;
RemoveNamedItem (name)--Deletes the node with the NodeName property value equal to name;
SetNamedItem (node)--adds node to the list, indexed by its NodeName property;
Item (POS)--like the nodelist, returns a node in the position POS;
Note: Keep in mind that these methods return a attr node, not an attribute value.

The NamedNodeMap object also has a length property to indicate the number of nodes it contains.
When NamedNodeMap is used to represent an attribute, where each node is a attr node, the NodeName property is set to the attribute name, and the NodeValue property is set to the value of the attribute. For example, suppose you have such an element:
<p style= "color:red" id= "P1" >hello world!</p>
Also, suppose the variable op contains a reference to this element. You can then access the value of the id attribute:
var sId = OP.attributes.getNamedItem ("id"). nodevalue;
Of course, you can also use numeric methods to access the ID attribute, but this is slightly less intuitive:
var sId = OP.attributes.item (1). NodeValue;
You can also change the id attribute by assigning a new value to the NodeValue property:
OP.attributes.getNamedItem ("id"). nodevalue= "NewId";
The attr node also has a Value property that is completely equivalent (and also fully synchronized) to the NodeValue property, and has the Name property and the NodeName property synchronized. We are free to use these properties to modify or change attributes.
Because this method is somewhat cumbersome, the DOM defines three element methods to help access the attributes:
GetAttribute (name)--equals Attributes.getnameditem (name). value;
SetAttribute (Name,newvalue)--equals Attribute.getnameditem (name). Value=newvalue;
RemoveAttribute (name)--equals Attribute.removenameditem (name).

4. Access to the specified node
(1) getElementsByTagName ()
The core (XML) DOM defines the getElementsByTagName () method that returns a nodelist that contains all the TagName (signed) attributes equal to the element of a specified value. In the Element object, the TagName attribute is always equal to the name immediately following the less than sign-for example, the tagname of is "img". The next line of code returns a list of all the elements in the document:
var Oimgs = document.getelementsbytagname ("img");
After all the graphics have been stored in the OIMGS, you can access them one at a getelementsbytagname, just by using the square brackets or the item () method (() to return a nodelist like childnodes):
alert (oimgs[0].tagname); Outputs "IMG"
If you just want to get all the images in the first paragraph of a page, you can do so by calling getElementsByTagName () on the first paragraph element, like this:
var oPs = document.getelementbytagname ("P");
var oimgsinp = ops[0].getelementbytagname ("img");
You can use an asterisk method to get all the elements in the document:
var oallelements = document.getElementsByTagName ("*");
When the argument is an asterisk, IE6.0 does not return all the elements. You must use document.all to replace it.
(2) Getelementsbyname ()
The HTML DOM defines the Getelementsbyname (), which is used to get all the elements that have the name attribute equal to the specified value.
(3) getElementById ()
This is the second method defined by the HTML DOM that returns an element with an id attribute equal to the specified value. In HTML, the id attribute is unique-this means that no two elements can share the same ID. There is no doubt that 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 also returns the element. This is a bug and a problem that must be very careful.

5. Create a new node
A few of the most common methods are
Createdocumentfragment ()--Create a document fragment node
CreateElement (tagname)--Create an element with a label named TagName
createTextNode (text)--Create a text node that contains text texts

createelement (), createTextNode (), AppendChild ()
Copy Code code as follows:

<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>
<body onload= "CreateMessage ()" >
</body>

RemoveChild (), ReplaceChild (), InsertBefore ()
Delete a node

Copy Code code as follows:

<title>removechild () example</title>
<script type= "Text/javascript" >
function Removemessage () {
var OP = document.body.getElementsByTagName ("P") [0];
OP.parentNode.removeChild (OP);
}
</script>
<body onload= "Removemessage ()" >
<p>hello world!</p>
</body>

Replace
<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>
<body onload= "Replacemessage ()" >
<p>hello world!</p>
</body>
Before the new message is added to the old message
<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>
<body onload= "Insertmessage ()" >
<p>hello world!</p>
</body>

Createdocumentfragment ()
Once the node is added to the document.body (or its descendant node), the page is updated and reflects the change. This is fine for a small number of updates, however, if you add a large amount of data to the document, the process may be slow if you are adding them one by one. To solve this problem, you can create a fragment of the document, attach all the new nodes to it, and then add the contents of the document fragment to the documents at once, if you want to create 10 new paragraphs

Copy Code code as follows:

<title>insertbefore () example</title>
<script type= "Text/javascript" >
function Addmessages () {
var arrtext = ["A", "second", "third", "fourth", "fifth", "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>
<body onload= "addmessages ()" >
</body>

6. Make attributes like attributes
In most cases, all attributes contained in an HTML DOM element are available as attributes.
Suppose you have the following image elements:

If you want to use the core DOM to get and set the SRC and border attributes, use the getattribute () and SetAttribute () methods:
Alert (Oimg.getattribute ("src"));
Alert (Oimg.getattribute ("border"));
Oimg.setattribute ("src", "mypicture2.jpg");
Oimg.setattribute ("Border", 1);
However, using the HTML DOM, you can use properties of the same name to get and set these values:
alert (OIMG.SRC);
alert (Oimg.border);
Oimg.src= "Mypicture2.jpg";
Oimg.border = "1";
A unique exception to the attribute name and property name is the class attribute, which is used to specify a CSS class that is applied to an element because class is a reserved word in ECMAScript, and in JavaScript it cannot be used as a variable name, property name, or all function name. Hence, the corresponding attribute name becomes the classname;
Note: IE has a big problem with setattribute (), and it is best to use attributes as much as possible.

7.table method
To help create tables, the HTML Dom adds features and methods to elements such as <table/>,<tbody/> and <tr/>.
Add the following to the <table/> element:
td> Delete <tfoot/> element
Attributes/Methods description
caption point to <caption/> element and put it in table
tbodies <tbody/> elements Collection
tFoot pointing <tfoot/> meta Vegetarian (if present)
tHead point to <thead/> Element (if present)
rows table The collection of all rows in the
createthead () create <thead/> elements and place them in a table
Createtfoo D () Create <tfoot/> element and place it in table
createcpation () Create <caption/> element and put it into table Grid
deletethead () Delete <thead/> elements
deletetfood ()
deletecaption () Delete <caption/> element
deleterow (position) deletes a row at the specified location
insertrow (position) inserts a new line at the specified location in the Rows collection /td>

The <tbody/> element adds the following
Features/methods Description
Rows A collection of all the rows in <tbody/>
DeleteRow (position) Delete a row at a specified location
InsertRow (position) Inserts a new row at the specified position in the Rows collection

The <tr/> element adds the following
Features/methods Description
Cells A collection of all the cells in the <tr/> element
Deletecell (postion) Delete a cell at a given location
InsertCell (postion) Inserts a new cell at the point location of the Cells collection

8. Traverse Dom
Nodeiterator,treewalker
DOM Level2 features that are only available in Mozilla and Konqueror/safari, and this is not a description of
Here are some articles about DOM operations
Dynamic deletion of table multiple rows for JavaScript DOM operations
JavaScript DOM Add Event

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.