1.Create Node
var anchor = document.createElement("a"); // Create an <a> node
anchor.setAttribute("name", "TOC"); // Give it a name
toc.appendChild(anchor); // Insert it
anchor.appendChild(document.createTextNode("Table Of Contents"));
2.Search Node
function countTags(n) { // n is a Node
var numtags = 0; // Initialize the tag counter
if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) // Check if n is an Element
numtags++; // Increment the counter if so
var children = n.childNodes; // Now get all children of n
for(var i=0; i < children.length; i++) { // Loop through the children
numtags += countTags(children[i]); // Recurse on each one
}
return numtags; // Return the total number of tags
}
3.Node Type
Interface | nodeType constant | nodeType value |
---|---|---|
Element | Node.ELEMENT_NODE | 1 |
Text | Node.TEXT_NODE | 3 |
Document | Node.DOCUMENT_NODE | 9 |
Comment | Node.COMMENT_NODE | 8 |
DocumentFragment | Node.DOCUMENT_FRAGMENT_NODE | 11 |
Attr | Node.ATTRIBUTE_NODE | 2 |
4.Modify Node
function reverse(n) { // Reverse the order of the children of Node n
var kids = n.childNodes; // Get the list of children
var numkids = kids.length; // Figure out how many children there are
for(var i = numkids-1; i >= 0; i--) { // Loop backward through the children
var c = n.removeChild(kids[i]); // Remove a child
n.appendChild(c); // Put it back at its new position
}
}
5.Replace Node
function embolden(node) {
var bold = document.createElement("b"); // Create a new <b> element
var parent = node.parentNode; // Get the parent of the node
parent.replaceChild(bold, node); // Replace the node with the <b> tag
bold.appendChild(node); // Make the node a child of the <b> tag
}
没有评论:
发表评论