DOM element Basic Operation Method API, first record, easy to use later.
The consortium DOM and JavaScript are easily confusing. The DOM is an API for HTML and XML documents that provides a structured representation of the document and defines how to access it through a script
Ask the document structure. JavaScript is the language used to access and process the DOM. Without dom,javascript, there are no web pages and concepts that make up the page elements. Document
Each element in is part of the DOM, which allows JavaScript to access the elements ' properties and methods.
Dom is independent of the specific programming language and typically accesses DOM through JavaScript, but is not strictly required. You can use any scripting language to access the DOM, which is
Work on its consistent API. Table 3-1 lists some useful properties for the DOM element, and table 3-2 lists some useful methods.
Table 3-1 DOM element properties for processing XML documents
Property name Description
ChildNodes returns an array of all child elements of the current element
FirstChild returns the first subordinate child element of the current element
LastChild returns the last child element of the current element
NextSibling returns the element immediately following the current element
NODEVALUE specifies a read/write property that represents the value of an element
ParentNode returns the parent node of the element
PreviousSibling returns elements immediately preceding the current element
Table 3-2 DOM element methods for traversing XML documents
Method Name Description
getElementById (ID) (document) Gets the elements in the document with the specified unique id attribute value
getElementsByTagName (name) returns an array of child elements in the current element that have the specified tag name
HasChildNodes () returns a Boolean value indicating whether the element has child elements
GetAttribute (name) returns the attribute value of the element, which is specified by name
With the Web DOM, you can write simple cross-browser scripts that take advantage of the power and flexibility of XML as a communication interface between browsers and servers
Quality.
As you can see from the example below, it is easy to read XML documents using JavaScript that follows the DOM of the consortium. The code listing 3-3 shows the server returned to the browser
The contents of the XML document. This is a simple list of American States, divided by region.
Table 3-3 the Consortium DOM properties and methods used to dynamically create content
Attribute/Method Description
The CreateElement method on the document.createelement (tagName) Document object can create elements that are specified by TagName. If the string div is used as the method argument,
A DIV element is generated
The createTextNode method of the document.createTextNode (text) Document object creates a node that contains static text
The <element>.appendchild (Childnode) AppendChild method adds the specified node to the list of child nodes of the current element (as a new child node). For example
You can add an option element as a child node of the SELECT element
<element>.getattribute (name)
<element>.setattribute (name, value) Each of these methods gets and sets the value of the Name property in the element
<element>.insertbefore (NewNode, TargetNode) inserts the node NewNode in front of the TargetNode element as the child of the current element
<element>.removeattribute (name) removes property name from the element
<element>.removechild (Childnode) This method deletes a child element from the element Childnode
<element>.replacechild (NewNode, OldNode) This method replaces the node OldNode with a node NewNode
<element>.haschildnodes () This method returns a Boolean value indicating whether the element has child elements
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.
Attribute/method Type/return type description
The name of the NodeName String node, defined according to the type of the node
The value of the NodeValue String node, defined based on the type of node
One of the type constant values of the NodeType number node
Ownerdocument document points to the documentation that this node belongs to
FirstChild node points to the first nodes in the ChildNodes list
LastChild node points to the last nodes in the ChildNodes list
ChildNodes nodelist List of all child nodes
PreviousSibling node points to the previous sibling; If this node is the first sibling node, then the value is null
NextSibling node points to the latter sibling; If this node is the last sibling node, then the value is null
HasChildNodes () Boolean when childnodes contains one or more nodes, returns true
The attributes NamedNodeMap contains a Attr object that represents an attribute of an element; only for ELEMENT nodes
AppendChild (node) node adds node to the end of ChildNodes
RemoveChild (node) node deletes node from ChildNodes
ReplaceChild (Newnode,oldnode) Node replaces OldNode in childnodes with NewNode
InsertBefore (Newnode,refnode) Node inserts 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
1
2
3 <title>dom example</title>
4
5 <body>
6 <p>hello world!</p>
7 <p>isn ' t this exciting?</p>
8 <p>you ' re learning to-use the dom!</p>
9 </body>
10
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 the child nodes 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 special
The value of sex. 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 can
Use these properties at will 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 an element containing all tagname (signed) attributes equal to a specified value.
NodeList. 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
Returns a list of all elements in the document:
var Oimgs = document.getelementsbytagname ("img");
After all the graphics are stored in the Oimgs, just use the square brackets or the item () method (getElementsByTagName () to return a nodelist as ChildNodes),
You can access these nodes individually as you would access the child nodes:
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 be
Enjoy 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 ()
1
2
3 <title>createelement () example</title>
4 <script type= "Text/javascript" >
5 function CreateMessage () {
6 var OP = document.createelement ("P");
7 var otext = document.createTextNode ("Hello world!");
8 Op.appendchild (Otext);
9 Document.body.appendChild (OP);
10}
</script>
<body onload= "CreateMessage ()" >
</body>
15
RemoveChild (), ReplaceChild (), InsertBefore ()
Delete a node
1
2
3 <title>removechild () example</title>
4 <script type= "Text/javascript" >
5 function Removemessage () {
6 var OP = document.body.getElementsByTagName ("P") [0];
7 OP.parentNode.removeChild (OP);
8}
9 </script>
Ten
One <body onload= "Removemessage ()" >
<p>hello world!</p>
</body>
14
Replace
1
2
3 <title>replacechild () example</title>
4 <script type= "Text/javascript" >
5 function Replacemessage () {
6 var onewp = document.createelement ("P");
7 var otext = document.createTextNode ("Hello universe!");
8 Onewp.appendchild (Otext);
9 var ooldp = document.body.getElementsByTagName ("P") [0];
OOldP.parentNode.replaceChild (ONEWP, OOLDP);
11}
</script>
<body onload= "Replacemessage ()" >
<p>hello world!</p>
</body>
17
Before the new message is added to the old message
1
2
3 <title>insertbefore () example</title>
4 <script type= "Text/javascript" >
5 function Insertmessage () {
6 var onewp = document.createelement ("P");
7 var otext = document.createTextNode ("Hello universe!");
8 Onewp.appendchild (Otext);
9 var ooldp = document.getElementsByTagName ("P") [0];
Document.body.insertBefore (ONEWP, OOLDP);
11}
</script>
<body onload= "Insertmessage ()" >
<p>hello world!</p>
</body>
17
Createdocumentfragment ()
Once the node is added to the document.body (or its descendant node), the page is updated and reflects the change. For a small amount of updates, which is good, however
, this process can be very slow when you add a large amount of data to the document, if you add those changes individually. To solve this problem, you can create a document that is broken
, add all the new nodes to it, and then append the contents of the document fragment to the documents once, if you want to create 10 new paragraphs
1
2
3 <title>insertbefore () example</title>
4 <script type= "Text/javascript" >
5 function Addmessages () {
6 var arrtext = ["A", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
"Ninth", "tenth"];
7
8 var ofragment = Document.createdocumentfragment ();
9
for (Var i=0 i < arrtext.length; i++) {
One var OP = document.createelement ("P");
var otext = document.createTextNode (Arrtext[i]);
Op.appendchild (Otext);
Ofragment.appendchild (OP);
15}
16
Document.body.appendChild (ofragment);
18
19}
</script>
<body onload= "addmessages ()" >
23
</body>
25
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 ECMAScript in the
Left word, 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:
Feature/Method description
Caption points to <caption/> elements and puts them into a table
Collection of tbodies <tbody/> elements
TFoot point to <tfoot/> Element (if present)
THead point to <thead/> Element (if present)
Collection of all rows in the rows table
Createthead () Create <thead/> elements and put them into a table
Createtfood () Create <tfoot/> elements and put them into a table
Createcpation () Create <caption/> elements and put them into a table
Deletethead () Delete <thead/> element
Deletetfood () Delete <tfoot/> element
Deletecaption () Delete <caption/> element
DeleteRow (position) deletes the row at the specified location
InsertRow (position) inserts a new row at the specified position in the Rows collection
The <tbody/> element adds the following
Feature/Method description
Collection of all rows in rows <tbody/>
DeleteRow (position) deletes the row at the specified location
InsertRow (position) inserts a new row at the specified position in the Rows collection
The <tr/> element adds the following
Feature/Method description
Collection of all cells in the cells <tr/> element
Deletecell (postion) deletes a cell at a given location
InsertCell (postion) Inserts a new cell at the point position of the Cells collection