内容显示页
 
类别:JavaScript | 浏览(834) | 2007-5-24 22:43:46 | 关闭广告

What this section covers:

Creating nodes
Duplicating nodes
Inserting nodes
Removing nodes
Replacing nodes
Manipulating nodes
Finding nodes
Node properties
Traversing the node tree

This section contains a list of some of the most useful methods and properties provided by
the Document Object Model. They are arranged by task.

Methods

These methods are part of the DOM Core. This isn’t a complete list of all the methods
available. These are the most useful methods.

Creating nodes

Use these methods to create new nodes.

createElement

The createElement method creates a new element node with the specified tag name. This
method returns a reference to the newly created element:

reference = document.createElement(element)

The method takes a single parameter: the name of the element to be created. This is a string:

reference = document.createElement("p")
reference = document.createElement("h1")

The reference returned by createElement is a node object. It is an element node, so its
nodeType property will have a value of 1:

var para = document.createElement("p");

In this example, para.nodeType would return a value of 1. para.nodeName would return a
value of “p” or “P”.

An element created with createElement is not automatically added to the document.
The new node has no parentNode property. Instead, it exists only in JavaScript as a


DocumentFragment. To add the DocumentFragment to your document, you will need to
use the appendChild or insertBefore methods (see “Inserting nodes”) or else
replaceChild (see “Replacing nodes”):

var para = document.createElement("p");
document.body.appendChild(para);

This example will create a paragraph element and append the newly created element as
the lastChild of the body element.

You can apply methods to the newly created element at any time. For instance, you can set
an attribute on the element even before the element is inserted into the document (see
“Manipulating nodes”):

var para = document.createElement("p");
para.setAttribute("title","My paragraph");
document.body.appendChild(para);

Alternatively, you can manipulate the newly created node after it has been inserted into
the document:

var para = document.createElement("p");
document.body.appendChild(para);
para.setAttribute("title","My paragraph");

createTextNode

The createTextNode method creates a new text node containing the specified text. This
method returns a reference to the newly created text node:

reference = document.createTextNode(text)

The method takes a single parameter: the string of text to be created:

reference = document.createTextNode("hello world")

The reference returned by createTextNode is a node object. It is a text node, so its
nodeType property will have a value of 3:

var message = document.createTextNode("hello world");

In this example, message.nodeType would return a value of 1. message.nodeName would
return a value of “#text”.

A text node created with createTextNode is not automatically added to the document.
The new node has no parentNode property. To add the newly created text to your document, you will need to use the appendChild or insertBefore methods (see “Inserting
Nodes”) or else replaceChild (see “Replacing Nodes”):

var message = document.createTextNode("hello world");
var container = document.getElementById("intro");
container.appendChild(message);

REFERENCE


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

This example will create a text node with the value “hello world”. This text node is then
appended to the element with the id “intro”.

The createTextNode method is often used in conjunction with createElement method to
create chunks of markup that can then be inserted into the document:

var message = document.createTextNode("hello world");
var container = document.createElement("p");
container.appendChild(message);
document.body.appendChild(message);

In this example, a text node containing the string “hello world” is created. The
createTextNode method returns the reference message. A paragraph element is created
using the createElement method, which returns the reference container. The message
text node is placed inside the container element node using the appendChild method.
This updated container element is then appended to the body element of the document.

Duplicating nodes

The Document Object Model provides a method for copying a node.

cloneNode

The cloneNode method creates a copy of a specified node. This method returns a reference to the newly cloned node:

reference = node.cloneNode(deep)

The method takes a single parameter that can have a Boolean value of true or false. This
parameter specifies whether or not the newly created node contains the same child nodes
as the copied node. If the parameter’s value is true, the newly created node will have all
the same children as the node from which it was cloned. If it is false, the newly created
node will have no child nodes. If the node is an element node, it means that any text
within the original element will not be duplicated (the text is a child node), but attributes
will be duplicated:

reference = node.cloneNode(true)
reference = node.cloneNode(false)

The reference returned by the cloneNode method is a node object. This node will have the
same nodeType and nodeName properties as the original node from which it was cloned:

var para = document.createElement("p");
var newpara = para.cloneNode(false);

This example creates a new element node: para. Then, another new element node, new-
para, is created, which is a clone of the para element node. The value of para.nodeType is
1 (an element node) so the value of newpara.nodeType is also 1.


REFERENCE

Here’s another example:

var message = document.createElement("hello world");
var newmessage = message.cloneNode(false);

In this case, a new text node is created: message. This text node is cloned to make newmessage.
The value of newmessage.nodeType is 3 (a text node) because the value of message.nodeType
is 3. newmessage.nodeName is “#text”, the same value as message.nodeName.

In the following example, a node is cloned complete with child nodes:

var para = document.createElement("p");
var message = document.createTextNode("hello world");
para.appendChild(message);
var newpara = para.cloneNode(true);

Because the value true was passed to para.cloneNode, the newly created element node,
newpara, has a child text node with the value “hello world”.

Here, a node is cloned without cloning the node’s children:

var para = document.createElement("p");
var message = document.createTextNode("hello world");
para.appendChild(message);
var newpara = para.cloneNode(false);

The new node, newpara, is an element node just like the original para. But whereas para
had a child text node with the value “hello world”, newpara has no child nodes.

When a node is duplicated using the cloneNode method, the newly created node is not
automatically added to the document. The new node has no parentNode property. You will
need to use the appendChild or insertBefore methods (see “Inserting Nodes”) or else
replaceChild (see “Replacing nodes”):

var para = document.createElement("p");
var message = document.createTextNode("hello world");
para.appendChild(message);
document.body.appendChild(para);
var newpara = para.cloneNode(true);
document.body.appendChild(newpara);

In this example, a new paragraph element called para is created. Also, a new text node called
message is created. The message text node is inserted into the para element node and then
para is inserted into the body of the document. Using the cloneNode method, para is duplicated (along with its child node) to create the element node: newpara. newpara is inserted
into the body of the document. Two identical paragraphs of text have been added to the
document.

If you clone an element that has a unique id, you should always change the value of the
new element’s id. An id attribute must be unique within a document.


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

Inserting nodes

There are two methods for inserting nodes into a document.

appendChild

The appendChild method adds a new child node to an element node:

reference = elment.appendChild(newChild)

The new child node becomes the last child node of the element to which it has been
appended. This method returns a reference to the newly appended node.

This method is usually used in conjunction with createElement and createTextNode,
which are used to generate new nodes.

In this example, a paragraph element, para, is created with createElement. A text node,
message, is creating with createTextNode. The text node is then inserted into the
paragraph using appendChild:

var para = document.createElement("p");
var message = document.createTextNode("hello world");
para.appendChild(message);

The para element (and its child, message) can then be inserted into the structure of the
document, again using appendChild:

document.body.appendChild(para);

In this case, the para element is appended to the body of the document.

New nodes can be attached to any element in the document. In the following example, a
new text node is appended to the element in the document with the id of “headline”:

var message = document.createTextNode("hello world");
var container = document.getElementById("headline");
container.appendChild(message);

The lastChild property of container is the new text node with the value “hello world”.

As well as working with newly created elements, appendChild can also be used to move
existing elements in the document.

In this example, there is one element with the id “content” and another with the id
“fineprint”. The “fineprint” element is moved from wherever it was in the document and is
appended at the end of the “content” element:

var message = document.getElementById("fineprint");
var container = document.getElementById("content");
container.appendChild(message);


The element with the id “fineprint” is first removed from the document tree and then
reinserted in its new position as the last child node of the “content” element.

insertBefore

The insertBefore method is used to insert a new node into an element before a specified
child node of the element:

reference = element.insertBefore(newNode,targetNode)

The node newNode is inserted into the node element before the node targetNode. The
node targetNode must be a child node of element. If targetNode is not specified, newNode
will be appended at the end of the child nodes of element. In that case, it behaves just like
the appendChild method.

The insertBefore method is often used with createElement and createTextNode to
insert newly created nodes into the document tree.

In this example, a document has an element with the id “content”. This element contains
an element with the id “fineprint”. A new paragraph element is created using
createElement. This newly created element is then inserted into the “content” element,
right before the “fineprint” element:

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
var para = document.createElement("p");
container.insertBefore(para,message);

If the node being inserted has any child nodes, these will also be inserted before the
target node:

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
var para = document.createElement("p");
var text = document.createTextNode("Here comes the fineprint");
para.appendChild(text);
container.insertBefore(para,message);

As well as working with newly created nodes, insertBefore can also be used to move
existing nodes in the document.

In this example, a document has an element with the id “content”. This element contains
an element with the id “fineprint”. Elsewhere in the document, there is an element with
the id “headline”. The “headline” element is moved into the “content” element and placed
before the “fineprint” element:

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
var announcement = document.getElementById("headline");
container.insertBefore(announcement,message);

REFERENCE


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

The element with the id “headline” is first removed from the document tree and then
reinserted into its new position before the “fineprint” element inside the “content” element.

Removing nodes

The DOM provides a method for removing nodes from a document.

removeChild

The removeChild method removes a child node from a specified parent element:

reference = element.removeChild(node)

This method returns a reference to the node that has been removed.

When a node is removed with removeChild, any child nodes contained by that node are
also removed.

In this example, the element with the id “content” contains an element with the id
“fineprint”. The “fineprint” element is removed from the “content” element using
removeChild:

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
container.removeChild(message);

If you want to remove a node but you don’t have a reference to its parent node, you can
use the parentNode property of the node you want to remove:

var message = document.getElementById("fineprint");
var container = message.parentNode;
container.removeChild(message);

If you want to move a node from one part of the document tree to another, there is no
need to use removeChild. The appendChild and insertBefore methods will automatically
remove nodes from the document tree before reinserting them in their new positions.

Replacing nodes

The DOM provides a method for replacing nodes in a document tree.

replaceChild

The replaceChild method replaces one child node of a specified parent element with
another node:

reference = element.replaceChild(newChild,oldChild)

The oldChild node must be a child node of element. This method returns a reference to
the node that has been replaced.


REFERENCE

In this example, an element with the id “content” contains an element with the id
“fineprint”. A new paragraph element is created using createElement. Using replaceChild,
this newly created element replaces the “fineprint” element:

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
var para = document.createElement("p");
container.replaceChild(para,message);

If the new node has any child nodes, they will also be inserted into the document tree.

The replaceChild method also works on nodes that are already part of the document
tree. If the newChild node already exists in the document tree, it will first be removed
before replacing the oldChild node.

In this example, the element node with the id “headline” replaces the element with the id
“fineprint” within the element “content”:

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
var announcement = document.getElementById("headline");
container.replaceChild(announcement,message);

This example does the same as the previous one, but this time a reference to the replaced
node is used to reinsert it into the document (as the last child node of “content”):

var container = document.getElementById("content");
var message = document.getElementById("fineprint");
var announcement = document.getElementById("headline");
var oldmessage = container.replaceChild(announcement,message);
container.appendChild(oldmessage);

Manipulating nodes

The DOM provides a mechanism for manipulating attribute nodes.

setAttribute

The setAttribute method adds a new attribute value or changes the value of an existing
attribute of a specified element node:

element.setAttribute(attributeName,attributeValue)

The name and the value of the attribute are passed to the method as strings. If this attrib
ute already exists, its value will be updated. If the named attribute doesn’t exist, it will be
created and given a value. The setAttribute method can only be used on element nodes.


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

In this example, a title attribute with the value “this is important” is added to an element
with the id “fineprint”:

var message = document.getElementById("fineprint");
message.setAttribute("title","this is important");

Regardless of whether or not the element had an existing title attribute, it now has a
title attribute with the value “this is important”.

Attribute nodes can be set on elements that have not yet been added to the document
tree. If you create a new element using the createElement method, you can set attributes
on that element before adding it to the document tree:

var para = document.createElement("p");
para.setAttribute("id","fineprint");
var container = document.getElementById("content");
container.appendChild(para);

The corollary to setAttribute is getAttribute, which allows you to retrieve the value of
an attribute.

Finding nodes

The Document Object Model provides a number of methods for locating nodes in a
document tree.

getAttribute

The getAttribute method returns the value of a named attribute node of a specified
element:

attributeValue = element.getAttribute(attributeName)

The name of the attribute is passed to the method as a string. The value of the named
attribute is returned as a string. If the named attribute doesn’t exist, getAttribute returns
an empty string.

This example retrieves the title attribute of an element with the id “fineprint” and stores
it in a variable called titletext:

var message = document.getElementById("fineprint");
var titletext = message.getAttribute("title");

This next example takes the value of the title attribute and creates a new text node with
that value. This text node is then appended to the end of the “fineprint” element:

var message = document.getElementById("fineprint");
var titletext = message.getAttribute("title");
var newtext = document.createTextNode(titletext);
message.appendChild(titletext);


REFERENCE

The corollary to getAttribute is setAttribute, which allows you to specify the value of
an attribute.

getElementById

The getElementById method finds an element with a specified id attribute:

element = document.getElementById(ID)

This method returns an element node with the specified id. If there is no such element,
getElementById returns null. The getElementById method can only be applied to the
document object.

The element node returned by getElementById is an object, complete with properties
such as nodeName, nodeType, parentNode, childNodes, etc.

This example retrieves the element with the id “fineprint” and stores it in the variable
message. The parent node of message, also an element, is stored in the variable container:

var message = document.getElementById("fineprint");
var container = message.parentNode;

If an element has an id, using the getElementById method is the simplest and quickest
way to reference that element. You can then apply methods like setAttribute,
cloneNode, or appendChild.

The following example finds an element with the id “fineprint” and stores it in the variable
message. The title attribute of this element is then updated with the value “this is
important”:

var message = document.getElementById("fineprint");
message.setAttribute("title","this is important");

The id of an element should be unique within a document. If more than one element
share the same id, the getElementById method may behave unpredictably.

getElementsByTagName

The getElementsByTagName method finds all the elements with a specified tag name:

elements = document.getElementsByTagName(tagName)

This method returns a list of elements. This list can be treated as an array. The length
property of the list is equal to the number of elements in the document with the specified
tag name. Each element in the array is an object, complete with properties such as
nodeName, nodeType, parentNode, childNodes, etc.

This example retrieves all the paragraphs in a document. The length property of the
returned list is stored as the variable howmany:

var paras = document.getElementsByTagName("p");
var howmany = paras.length;


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

The getElementsByTagName method is often used together with a for loop to go through
each element in the returned list. In this way, each element can be queried or manipulated
using methods like setAttribute, cloneNode, appendChild, etc.

The following example loops through all the paragraphs in a document and sets the title
attribute of each one to a blank string:

var paras = document.getElementsByTagName("p");

for (var i=0; i < paras.length; i++) {
paras[i].setAttribute("title","");

}

In that example, paras is a nodeList. The items in this list can be accessed like any other
array: paras[0], paras[1], paras[2], and so on. Alternatively, you can use the item
method: paras.item(0), paras.item(1), paras.item(2), and so on.

The getElementsByTagName method doesn’t have to be used on the entire document.
It can also be used to find elements with a specified tag name that are children of a specified element.

In the following example, a document contains an element with the id “content”.
The getElementsByTagName method is applied to this element to find all the paragraphs
it contains:

var container = document.getElementById("content");
var paras = container.getElementsByTagName("p");
var howmany = paras.length;

The variable howmany now contains the number of paragraphs within the “content” element, not the number of paragraphs within the entire document.

hasChildNodes

The hasChildNodes method can be used to find out if a specified element has any child nodes:

booleanValue = element.hasChildNodes

This method returns a Boolean value of either true or false. If the specified element has
any children, hasChildNodes returns true. If the element has no children, hasChildNodes
returns false.

Text nodes and attributes cannot contain any children. The hasChildNodes method will
therefore always return a value of false.

This method is often used in an if statement. The following example finds an element
with the id “fineprint” and stores it in the variable message. If this element has any child
nodes, they are stored as an array in the variable children:

var message = document.getElementById("fineprint");

if (message.hasChildNodes) {
var children = message.childNodes;

}


The hasChildNodes method does not return the child nodes of an element. The child
nodes can be retrieved from the childNodes property of the element. If hasChildNodes
returns a value of false, the childNodes property is an empty array.

Likewise, if hasChildNodes returns false for a specified element, that element’s
firstChild and lastChild properties will be null.

Properties

Here are some properties of nodes in a DOM tree.

Node properties

Every node in a document has the following properties.

nodeName

The nodeName property returns a string containing the name of the specified node:

name = node.nodeName

If the specified node is an element node, the nodeName property will return the name of

the element. This is equivalent to the tagName property.
If the specified node is an attribute node, the nodeName property will return the name of
the attribute.

If the specified node is a text node, the nodeName property will return the string “#text”.
The nodeName property is read-only. It can be queried, but it can’t be manipulated directly.

nodeType

The nodeType property returns an integer indicating what type of node the specified node is:

integer = node.nodeType

There are twelve possible values for the nodeType property. The numerical value returned
by nodeType corresponds to one of twelve types of nodes:

1. ELEMENT_NODE
2. ATTRIBUTE_NODE
3. TEXT_NODE
4. CDATA_SECTION_NODE
5. ENTITY_REFERENCE_NODE
6. ENTITY_NODE
7. PROCESSING_INSTRUCTION_NODE
REFERENCE


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

8. COMMENT_NODE
9. DOCUMENT_NODE
10. DOCUMENT_TYPE_NODE
11. DOCUMENT_FRAGMENT_NODE
12. NOTATION_NODE
Of these twelve types, the first three are the most important. Most DOM Scripting on the
Web involves the manipulation of elements, attributes, and text nodes.

The nodeType property is often used in an if statement to ensure that illegal actions aren’t
performed on the wrong kind of node. In this example, a function takes a single argument,
mynode, which can be any element in the document. The function adds a title attribute
and value to the element. Before doing that, the nodeType property is checked to make
sure that mynode is in fact an element node:

function addTitle(mynode) {
if (mynode.nodeType == 1) {
mynode.setAttribute("title","this is important");
}
}

The nodeType property is read-only.

nodeValue

The nodeValue property returns the value of a specified node:

value = node.nodeValue

This property returns a string.
If the specified node is an attribute node, nodeValue returns the value of the attribute.
If the specified node is a text node, nodeValue returns the content of the text node.
If the specified node is an element node, nodeValue returns null.
The nodeValue property is read/write. However, you can’t set a value if it is defined as

null. In other words, you can’t set a nodeValue for an element node. You can set a value
for a text node.
This example will not work. It attempts to set a value for an element node:

var message = document.getElementById("fineprint");
message.nodeValue = "this won't work";

This example will probably work. It attempts to set a value for the first child of an element
node. As long as this first child is a text node, the new value is set:

var message = document.getElementById("fineprint");
message.firstChild.nodeValue = "this might work";


This example will certainly work. There is a test to make sure that the first child of the element is a text node:

var message = document.getElementById("fineprint");

if (message.firstChild.nodeType == 3) {
message.firstChild.nodeValue = "this will work";

}

The nodeValue property provides the simplest mechanism for updating the value of text
nodes. To update the value of attribute nodes, it is usually easier to use the setAttribute
method on the attribute’s parent element.

Traversing the node tree

These properties can be read to extract information about neighboring nodes.

childNodes

The childNodes property returns an array of child nodes for a specified element node:

nodeList = node.childNodes

The array returned by this method is a nodeList. Each node in the nodeList is a node
object. These node objects have all the usual node properties such as nodeType, nodeName,
nodeValue, etc.

Text nodes and attribute nodes cannot contain any children. Their childNodes property
always returns an empty array.

To find out if a node has any child nodes at all, use the hasChildNodes method.

To find out how many child nodes an element has, use the length property of the
childNodes array:

node.childNodes.length

If an element has only one child node, the childNodes property will still return an array of
nodes, not a single node. The length of the array will be 1. For instance, in a web page, the
document element has just one child, the html element. The value of document.
childNodes[0].nodeName is “HTML”.

The childNodes property is read-only. To add child nodes to an element, use the
appendChild or insertBefore methods. To remove child nodes from an element, use
the removeChild method. Whenever you use those methods, the childNodes property
of the altered element is updated automatically.

firstChild

The firstChild property returns the first child node of a specified element node:

reference = node.firstChild

REFERENCE


DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

This property returns a reference to a node object. This node object has all the usual node
properties such as nodeType, nodeName, nodeValue, etc.

Text nodes and attributes cannot contain any children. Their firstChild property always
returns a value of null.

The firstChild property of an element is equivalent to the first node in an element’s
childNodes nodeList:

reference = node.childNodes[0]

To find out if a node has any child nodes at all, use the hasChildNodes method. If a node
has no child nodes, the firstChild property will return a value of null.

The firstChild property is read-only.

lastChild

The lastChild property returns the last child node of a specified element node:

reference = node.lastChild

This property returns a reference to a node object. This node object has all the usual node
properties such as nodeType, nodeName, nodeValue, etc.

Text nodes and attributes cannot contain any children. Their lastChild property always
returns a value of null.

The lastChild property of an element is equivalent to the last node in an element’s
childNodes nodeList:

reference = node.childNodes[elementNode.childNodes.length-1]

To find out if a node has any child nodes at all, use the hasChildNodes method. If a node
has no child nodes, the lastChild property will return a value of null.

The lastChild property is read-only.

nextSibling

The nextSibling property returns the next node after a specified node:

reference = node.nextSibling

This property returns a reference to a node object. This node object has all the usual node
properties such as nodeType, nodeName, nodeValue, etc.

If there are no nodes immediately following the specified node, the nextSibling property
returns a value of null.

The nextSibling property is read-only.


REFERENCE

parentNode

The parentNode property returns the parent of a specified node:

reference = node.parentNode

This property returns a reference to a node object. This node object has all the usual node
properties such as nodeType, nodeName, nodeValue, etc.

The node that is returned will always be an element node, as only element nodes can contain children. The only exception to this is the document node, which has no parent. In that
case, parentNode returns a value of null.

The parentNode property is read-only.

previousSibling

The previousSibling property returns the previous node before a specified node:

reference = node.previousSibling

This property returns a reference to a node object. This node object has all the usual node
properties such as nodeType, nodeName, nodeValue, etc.

If there are no nodes immediately before the specified node, the previousSibling property returns a value of null.

The previousSibling property is read-only.


引用本页地址:http://www.yongfa365.com/item/a2ca314ee8e08f77.html
 
 
相关链接
 
网友评论:
姓名: 记住我
网址:
邮箱:
内容:
验证码:  验证码图片看不清? 换张图试试
 
   
 
 
文章分类
 
   

power by :柳永法(yongfa365)'Blog | model by :hibaidu | css by:众网友 | 京ICP备07011491号   我要统计  

本空间赞助商:北京中科兴联信息技术有限公司

QQ:64049027    E-mail:64049027<at>qq.com