W3C DOM Compatibility - Core
These compatibility tables detail support for the W3C DOM Core Level 1 and 2 modules in all modern browsers.
On this page I grouped the various W3C DOM methods and properties in nine tables. Basically you must know the first five tables by heart and you'll rarely need the last four tables.
1.Creating elements; HTML elements or text nodes.
2.Getting elements; Several ways of getting elements.
3.Node information; Once you found a node you need more information about it.
4.DOM tree; Walking the DOM tree. How to go from one node to another.
5.DOM traversal; DOM traversal properties that ignore text nodes.
6.Node manipulation. How to move nodes through the document.
7.Manipulating data. Data is always text, and there are some specialized methods for dealing with it.
8.Manipulating attributes. Terrible browser incompatibilities.
9.Miscellaneous methods and properties. You'll rarely need one of them.
10.Microsoft extensions to Level 1 DOM Core. Generally not interesting.
Creating elements
These two methods create new HTML elements which you can then insert into the document.
createElement()
Create a new element.
1 var x = document.createElement('div');
createTextNode()
Create a new text node.
1 var x = document.createTextNode('text'); 2 //Create a text node with content "text" and temporarily place it in x, which is later inserted into the document.
Getting elements
These methods are meant for getting the HTML elements you need from the document.
You must know these methods by heart.
getElementById()
Get the element with this ID
1 var x = document.getElementById('idName'); 2 //Take the element with id="idName", the method selects the first in the document. 3 //All others are ignored 4 //IE5-7 also return the element with name="idName".
getElementsByClassName()
Get a nodeList of the elements with this class.
1 var x = document.getElementsByClassName('someWords'); 2 //The first expression returns a nodeList with all elements that have a class value that contains "someWords". 3 var x = document.getElementsByClassName('someWords1 someWords2'); 4 //The second expression returns a nodeList will all elements that have a class value that contains both "someWords1" and "someWords2" (in any order).
getElementsByTagName()
Get all tags of this type.
1 var x = documentsByTagName('div'); 2 //Make x into a nodeList of all div's in the document, so [1] is the second div etc. 3 var x = y.getElementsByTagName('div'); 4 //Gets all divs that are descendants of node "y".
The * argument, which ought to select all elements in the document, doesn't work in IE5.5 Custom tags are not returned in Konqueror.
querySelectorAll()
Get a nodeList of elements by CSS
1 document.querySelectorAll('.textClass'). 2 document.querySelectorAll('.textClass + p') 3 //Return a nodeList with all elements that have a class value that contains "textClass"; 4 //or a nodeList with all paragraphs directly following such a element 5 //Essentially, this method allows you to use CSS syntax to retrieve elements
Node information
These four properties give basic information about all nodes. What they return depends on the node type. They are read-only, except for nodeValue.
There are three basic node types: element nodes (HTML tags), attribute nodes and text nodes. I test these properties for all these three types and added a fourth node type: the document node (the root of all other nodes).
You must know these properties by heart.
nodeName
1 x.nodeName 2 //The name of node.
nodeType
1 x.nodeType 2 //The type of node x.
nodeValue
1 x.nodeValue 2 //Get the value of node x. 3 x.nodeValue = 'Test'. 4 //Set the value of node x.
tagName
1 x.tagName 2 //Get the tag name of node x. 3 //Adivce: not to use tagName at all.
The DOM tree
Five properties and two arrays for walking through the DOM tree. Using these properties, you can reach nodes that are close to the current node in the document structure.
In general you shouldn't use too many of these properties. As soon as you're doing something like
x.parentNode.firstChild.nextSibling.children[2]
your code is too complicated. Complex relationships between nodes can suddenly and unexpectedly change when you alter the document structure, and altering the document structure is the point of the W3C DOM. In general you should use only one or two of these properties per action.
You must know these properties by heart.
childNodes[]
An array with all child nodes of the node.
1 x.childNodes[1] 2 //Get the second child node of node x. 3 //The childNodes nodeList consists of all child nodes of the elements, 4 //including(empty)text nodes and comment nodes.
children[]
An array with all child element nodes of the node.
1 x.children[1] 2 //Get the second child node of node x. 3 //Where childNodes holds all child nodes, children only holds those that are element nodes(HTML tags).
firstChild
The first child node of the node
x.firstChild //Get the first child node of node x.
lastChild
The last child node of the node
x.lastChild //Get the last child of node x.
nextSibling
The next sibling node of the node
x.nextSibling //Get the next child of the parent of x.
parentNode
The parent node of the node
x.parentNode //Get the parent node of x
previousSibling
The previous sibling node of the node
x.preivousSibling //Get the previous child of the parent of x.
sourceIndex
The index number of the node in the page source
x.sourceIndex //Get the sourceIndex of element x. //This is also the index number for the element in the document.getElementsByTagName('*') array ;
DOM Traversal
A few useful properties that should have been in the DOM from the start but mysteriously weren’t.
childElementCount
The number of element children
x.childElementCount
firstElementChild
The first child that is an element node
x.firstElementChild
lastElementChild
The last child that is an element node
x.lastElementChild
nextElementSibling
The next element node sibling
x.nextElementSibling
previousElementSibling
The previous element node sibling
x.previousElementSibling
Node manipulation
These five methods allow you to restructure the document. The average DOM script uses at least two of these methods.
The changes in the document structure are applied immediately, the whole DOM tree is altered. The browser, too, will immediately show the changes.
You must know these methods by heart.
appendChild()
Append a child node as the last node to an element.
x.appendChild(y) //Make node y the last child of node x. //If you append a node that's somewhere else in the document, it moves to the new position.
cloneNode()
Clone a node
x = y.cloneNode( true | false ) //Make node x a copy of node y. //If the argument is true, the entire tree below y is copied, //if it's false only the root node y is copied //Later you insert the clone into the document.
insertBefore()
Insert a node into the child nodes of an element
x.insertBefore( y, z ) //Insert node y as a child of node x just before node z.
removeChild()
Remove a child node from an element
//x.removeChild(y) //Remove child y of node x
replaceChild()
Replace a child node of an element by another child node
x.replaceChild( y, z ) //Replace node z, a child of node x, by node y.
Text data
These methods are for manipulating text data, i.e. the contents of text nodes.
appendData()
Append data to a text node
x.appendData(' some extra text ') //Appends the string "some extra text" to x, which must be a text node.
data
The content of a text node
x.data //The content of x, which must be a text node. //The same as x.nodeValue x.data = 'The new text'; //Can also be set
deleteData()
Delete text from a text node
x.deleteData(4, 3) //Delete some data from x, which must be a text node, //starting at the fifth character and deleting three characters //Second argument is required.
insertData()
Insert text into text node
x.insertData(4, ' and now for some extra text ') //Insert the string and now for some extra text after the fourth character into x, //which must be a text node.
normalize()
Merge adjacent text nodes into one node
x.normalize() //All child nodes of node x that are text nodes and have other text nodes as sibling, are merged. //This is in fact the reverse of splitText: text nodes that were split, come together again.
replaceData()
Replace text in a text node
x.replaceData( 4, 3, ' and for some new text ') //Replace three charaters, beginning at the fifth one, of node x, //which must be a text node, by the string "and for some new text".
splitText()
Split a text node into two text nodes
x.splitText(5) //Split the text node x at the 6th character. //x now contains the first part(char.0-5), while a new node is created( and becomes x.nextSibling ) //which contains the second part(char.6-end) of the orginial text.
substringData()
Take a substring of the text in the text node
x.substringData(4, 3) //Takes a substring of x, which must be a text node, starting at the fifth character and with a length of three characters. //Thus it's the same as the old substr() method fo strings.
wholeText()
The text of a text node plus the text in directly adjacent text nodes. Read only.
This read-only property is useful if you want to get the entire text at a certain point and don't want to e bothered by borders between text nodes.
Attributes
A bloody mess. Try influencing attributes in this order:
Try getting or setting a specific property, like x.id or y.onclick.
If there is no specific property, use getAttribute() or setAttribute().
If even that doesn't work, try any other method or property in the table below. Most have horrible browser incompatibility patterns, though.
Avoid attributes[]. It's worse than anything else.
In my view any method or property concerning attribute nodes should also work on the style attribute, event handlers and custom attributes. If not I judge the method or property incomplete.
attributes[index]
An array with the attributes of a node, accessed by index number,in the order they're defined in the source code.
x.attribute[1] //This array consists of all defined attributes in the source code order.
Do yourself a favour and don't use the indexed attribute array.
attributes[key]
An array with the attributes of a node, accessed by attribute name.
x.attributes['title'] //Get the title attribute object of node x. //If the node has no title attribute, it returns undefined //(except in IE, where it returns attribute object that has no value)
createAttribute()
setAttributeNode()
Create a new attribute node and append it to an element node.
z = document.createAttribute('title'); z.value = 'Test title'; x.setAttributeNode(z); //This creates a title attriute with a value and sets it on node x.
getAttribute()
Get the value of an attribute
x.getAttribute('title') //Gives the value of the title attribute of node x. //Upper case attribute names are also allowed
getAttributeNode()
Get an attribute node
x.getAttributeNode('title'); //Get the attribute object title of node x. This is an object, not al value.
hasAttribute()
Check if a node has a certain attribute.
x.hasAttribute('title') //Returns true when node x has attributes, false when it hasn't
name
The name of an attribute
x.name //The name of attribute node x.
removeAttribute()
Remove an attribute node
x.removeAttribute('title') //Remove the title attribute from node x.
removeAttributeNode()
Remove an attribute node
x.removeAttributeNode(x.attributes['title']) x.removeAttributeNode(x.attributes[1]) x.removeAttributeNode(x.getAttributeNode('title')) //Removes the attribute node. //There is litle difference with removeAttribute(), except in the argument.
setAttribute()
Set the value of an attribute.
x.setAttribute('title','hello') //Set the title attribute of node x to "hello". //The name and value are both strings.
setAttributeNode()
See createAttribute()
value
The value of an attribute
x.value //The value of attribute x.
Miscellaneous
A lot of miscellaneous methods and properties that you'll rarely need. I use only two of them in an actual script.
compareDocumentPosition()
Gives the relative place of one element compared to another
x.compareDocumentPosition(y) //Compares the document(DOM) position of element y to that element x.
contains()
Check whether an element contains another element
x.contains(y) //If node y is descendant of node x, the method returns true, else false.
createDocument()
Create a new document.
x = document.implementation.createDocument('', '', null) //Create a new XML document
createDocumentFragment()
Create a document fragment.
x = document.createDocumentFragment(); x.[fill with nodes]; document.[somewhere].appendChild(x); //Create a fragment, add a lot of nodes to it, and then insert it into the document. //Note that the fragment itself is not inserted, only its child nodes.
documentElement
The HTML tag
document.documentElement //Represents the root element of the XML document. //In any HTML document, the <html> element is of course the root element.
getElementByName()
Get elements by their name attribute.
var x = document.getElementsByName('test') //Create a nodeList with all elements that have name="text". //It should ignore elements with id="text"
hasChildNodes()
Check if the node has child nodes
x.hasChildNodes() //Returns true when node x has child; false when it hasn't.
item()
Access an item in an array.
document.getElementsByTagName('div').item[0]. //The same as document.getElementsByTagName('div')[0]. //You don't need item() at all in JavaScript
ownerDocument
The document that 'owns' the element.
x.ownerDocument //Refers to the document object that 'owns' node x. //This is the document node.
Microsoft extensions
As usual Microsoft has extended the standard somewhat. Though sometimes its extensions are brilliant (innerHTML springs to mind), in the case of the DOM Core they aren't.
Note the difference between W3C and Microsoft methods. The W3C methods are owned by the parent element of the node you want to adjust, the Microsoft methods by the node itself.
applyElement()
Something with nodex
var y = document.createElement('i'); x.applyElement(y) //The<i>element is inserted into element x, around the text.
clearAttributes()
Remove all attributes from a node.
x.clearAttributes() //Remove all attributes from node x.
mergeAttributes()
Copy all attributes of one node to another node.
x.mergeAttributes(y) //Copy all of node y's attribute to node x.
removeNode()
Remove a node.
x.removeNode(true | false) //Remove node x from the document. If you use the argument true its children are also removed; //if you use false they aren't. //Note that all text nodes count as children, too
replaceNode()
Replace a node by another node.
x.replaceNode(y) //Replace node x by node y.
swapNode()
Swap two nodes.
x.swapNode(y) //Put node x in node y's place and vice versa.
来自:http://www.quirksmode.org/dom/w3c_core.html#creatingelements