(Transfered)DOM最常用的方法和属性(Javascript DOM编程艺术,DOM Scripting)

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

the createElement method creates a new element node with the specified tag name.This method return s 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 method (see "insertBefore") 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.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>
  <div id="test">123</div>
  <script type="text/javascript">
    var innerObj=document.createElement("xgc");
    var outObj=document.getElementById("test");
    //document.body.getElementById("test").appendChild(innerObj);
    outObj.appendChild(innerObj);
    console.log(innerObj.nodeType);
    console.log(innerObj.nodeName);
  </script>
 </body>
</html>

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.

原文地址:https://www.cnblogs.com/hongjiumu/p/2667613.html