JavaScript DHTML/Development/DOM Content
Содержание
- 1 Adding/Replacing DOM Content
- 2 A DOM Core Document Analyzer
- 3 Check DOM Node object whether represents an HTML tag
- 4 Creating a Table: Using the insertBefore Method with DOM
- 5 CSS style sheet a "window" visual effect
- 6 Define a NodeFilter function to accept only "img" elements
- 7 If a DOM Node object is a Text object
- 8 Navigating Documents
- 9 recursively looks at node n and its descendants: replacing with their uppercase equivalents
Adding/Replacing DOM Content
<HTML>
<HEAD>
<TITLE>A Simple Page</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function modify() {
var newElem = document.createElement("P")
newElem.id = "newP"
var newText = document.createTextNode("This is the second paragraph.")
newElem.appendChild(newText)
document.body.appendChild(newElem)
document.getElementById("emphasis1").childNodes[0].nodeValue = "first "
}
</SCRIPT>
</HEAD>
<BODY>
<BUTTON onClick="modify()">Add/Replace Text</BUTTON>
<P ID="paragraph1">This is the <EM ID="emphasis1">one and only </EM>paragraph on the page.</P>
</BODY>
</HTML>
A DOM Core Document Analyzer
<html>
<head><title>DOM Core Analyzer</title>
<script language="JavaScript">
function analyzeDocument() {
var win = open("","results")
var doc = win.document
doc.open()
doc.writeln("<html><body>")
getDocumentStructure(document.documentElement, doc)
doc.writeln("</body></html>")
doc.close()
}
function getDocumentStructure(node, doc) {
doc.write(node.nodeName)
var children = node.childNodes
if(children != null && children.length > 0) {
doc.writeln("<ul>")
for(var i=0; i<children.length; ++i) {
var child = children.item(i)
doc.write("<li>")
getDocumentStructure(child, doc)
}
doc.writeln("</ul>")
}
}
</script>
</head>
<body onload="analyzeDocument()">
<h1 align="center">h1 center</h1>
<p> p <code> p code </code> after p </p>
<p>second p</p>
</body>
</html>
Check DOM Node object whether represents an HTML tag
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan. You may use, study, modify, and
distribute them for any purpose. Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<html>
<head>
<script>
// This function is passed a DOM Node object and checks to see if that node
// represents an HTML tag: i.e., if the node is an Element object. It
// recursively calls itself on each of the children of the node, testing
// them in the same way. It returns the total number of Element objects
// it encounters. If you invoke this function by passing it the
// Document object, it traverses the entire DOM tree.
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 total number of tags
}
</script>
</head>
<!-- Here"s an example of how the countTags() function might be used -->
<body onload="alert("This document has " + countTags(document) + " tags")">
This is a <i>sample</i> document.
</body>
</html>
Creating a Table: Using the insertBefore Method with DOM
<HTML>
<HEAD>
<TITLE> Building tables using DOM </TITLE>
</HEAD>
<BODY ID="bodyNode">
<SCRIPT LANGUAGE="JavaScript">
<!--
row1column1Node = document.createTextNode("test");
tableElement = document.createElement("TABLE");
tableBodyElement = document.createElement("TBODY");
tr1Element = document.createElement("TR");
tr1td1 = document.createElement("TD");
tr1td2 = tr1td1.cloneNode(true);
tr2td1 = tr1td1.cloneNode(false);
tr2td2 = tr1td1.cloneNode(true);
tr3td1 = tr1td1.cloneNode(false);
tr3td2 = tr1td1.cloneNode(false);
tr2 = tr1Element.cloneNode(true);
tr3 = tr1Element.cloneNode(false);
row1column2 = row1column1Node.cloneNode(false);
row2column1 = row1column1Node.cloneNode(true);
row2column2 = row1column1Node.cloneNode(false);
row3column1 = row1column1Node.cloneNode(true);
row3column2 = row1column1Node.cloneNode(false);
row1column2.nodeValue = "A ";
row2column1.nodeValue = "B ";
row2column2.nodeValue = "C ";
row3column1.nodeValue = "D ";
row3column2.nodeValue = "E ";
returnValue = tableElement.insertBefore(tableBodyElement);
tableBodyElement.insertBefore(tr3);
tableBodyElement.insertBefore(tr2, tr3);
tableBodyElement.insertBefore(tr1Element, tr2);
tr1Element.insertBefore(tr1td2);
tr1Element.insertBefore(tr1td1, tr1td2);
tr2.insertBefore(tr2td2);
tr2.insertBefore(tr2td1, tr2td2);
tr3.insertBefore(tr3td2);
tr3.insertBefore(tr3td1, tr3td2);
tr1td2.insertBefore(row1column2);
tr1td1.insertBefore(row1column1Node);
tr2td2.insertBefore(row2column2);
tr2td1.insertBefore(row2column1);
tr3td2.insertBefore(row3column2);
tr3td1.insertBefore(row3column1);
bodyNode.insertBefore(tableElement);
// -->
</SCRIPT>
</BODY>
</HTML>
CSS style sheet a "window" visual effect
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan. You may use, study, modify, and
distribute them for any purpose. Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<head>
<style type="text/css">
/**
* This is a CSS style sheet that defines three style rules that we use
* in the body of the document to create a "window" visual effect.
* The rules use positioning attributes to set the overall size of the window
* and the position of its components. Changing the size of the window
* requires careful changes to positioning attributes in all three rules.
**/
div.window { /* Specifies size and border of the window */
position: absolute; /* The position is specified elsewhere */
width: 300px; height: 200px; /* Window size, not including borders */
border: outset gray 3px; /* Note 3D "outset" border effect */
}
div.titlebar { /* Specifies position, size, and style of the titlebar */
position: absolute; /* It"s a positioned element */
top: 0px; height: 18px; /* titlebar is 18px + padding and borders */
width: 290px; /* 290 + 5px padding on left and right = 300 */
background-color: ActiveCaption; /* Use system titlebar color */
border-bottom: groove black 2px; /* Titlebar has border on bottom only */
padding: 3px 5px 2px 5px; /* Values clockwise: top, right, bottom, left */
font: caption; /* Use system font for titlebar */
}
div.content { /* Specifies size, position and scrolling for window content */
position: absolute; /* It"s a positioned element */
top: 25px; /* 18px title+2px border+3px+2px padding */
height: 165px; /* 200px total - 25px titlebar - 10px padding */
width: 290px; /* 300px width - 10px of padding */
padding: 5px; /* allow space on all four sides */
overflow: auto; /* give us scrollbars if we need them */
background-color: #ffffff; /* White background by default */
}
</style>
</head>
<body>
<!-- Here is how we define a window: a "window" div with a titlebar and -->
<!-- content div nested between them. Note how position is specified with -->
<!-- a style attribute that augments the styles from the style sheet -->
<div class="window" style="left: 10px; top: 10px; z-index: 10;">
<div class="titlebar">Test Window</div>
<div class="content">
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br> <!--Lots of lines to -->
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br> <!--demonstrate scrolling-->
</div>
</div>
<!-- Here"s another window with different position, color, and font weight -->
<div class="window" style="left: 170px; top: 140px; z-index: 20;">
<div class="titlebar">Another Window</div>
<div class="content" style="background-color:#d0d0d0; font-weight:bold;">
This is another window. Its <tt>z-index</tt> puts it on top of the other one.
</div>
</div>
</body>
Define a NodeFilter function to accept only "img" elements
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan. You may use, study, modify, and
distribute them for any purpose. Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
// Define a NodeFilter function to accept only <img> elements
function imgfilter(n) {
if (n.tagName == "IMG") return NodeFilter.FILTER_ACCEPT;
else return NodeFilter.FILTER_SKIP;
}
// Create a NodeIterator to find <img> tags
var images = document.createNodeIterator(document, // traverse entire document
/* only look at Element nodes */ NodeFilter.SHOW_ELEMENT,
/* filter out all but <img> */ imgfilter,
/* unused in HTML documents */ false);
// Use the iterator to loop through all images and do something with them
var image;
while((image = images.nextNode()) != null) {
image.style.visibility = "hidden"; // Process the image here
}
If a DOM Node object is a Text object
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan. You may use, study, modify, and
distribute them for any purpose. Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<html>
<head>
<script>
// This function is passed a DOM Node object and checks to see if that node
// represents a string of text: i.e., if the node is a Text object. If
// so, it returns the length of the string. If not, it recursively
// calls itself on each of the children of the node and adds up the
// total length of the text it finds. Note that it enumerates the
// children of a node using the firstChild and nextSibling properties.
// Note that the function does not recurse when it finds a Text node
// because Text nodes never have children.
function countCharacters(n) { // n is a Node
if (n.nodeType == 3 /*Node.TEXT_NODE*/) // Check if n is a Text object
return n.length; // If so, return its length.
// Otherwise, n may have children whose characters we need to count
var numchars = 0; // Used to hold total characters of the children
// Instead of using the childNodes property, this loop examines the
// children of n using the firstChild and nextSibling properties.
for(var m = n.firstChild; m != null; m = m.nextSibling) {
numchars += countCharacters(m); // Add up total characters found
}
return numchars; // Return total characters
}
</script>
</head>
<!--
The onload event handler is an example of how the countCharacters()
function might be used. Note that we only want to count the
characters in the <body> of the document, so we pass document.body
to the function.
-->
<body onload="alert("Document length: " + countCharacters(document.body))">
This is a sample document.<p>How long is it?
</body>
</html>
Navigate to Expression
The first child bodyNode.firstChild or
bodyNode.childNodes[0]
The second child bodyNode.childNodes[1]
The fourth or last child bodyNode.childNodes[4] or
bodyNode.lastChild
Root"s second child (the text node) from Node 1 Node1.nextSibling
Root"s third child from Node 1 Node1.nextSibling.nextSibling
Root"s last child Node1.nextSibling.nextSibling. nextSibling
Children of the fourth child Node1.nextSibling.nextSibling. nextSibling.childNodes[0]
The second <P> from the third <p> Node3.previousSibling.previous Sibling.previousSibling.childNodes[0]
The grandchild of the <BODY> tag. bodyNode.firstChild.firstChild
<BODY> root tag from a <P> tag Node1.parentNode
The grandchild of the <BODY> and bodyNode.firstChild.firstChild. parentNode.parentNode
back to the <body>
recursively looks at node n and its descendants: replacing with their uppercase equivalents
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan. You may use, study, modify, and
distribute them for any purpose. Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<html>
<script>
// This function recursively looks at node n and its descendants,
// replacing all Text nodes with their uppercase equivalents.
function uppercase(n) {
if (n.nodeType == 3 /*Node.TEXT_NODE*/) {
// If the node is a Text node, create a new Text node that
// holds the uppercase version of the node"s text, and use the
// replaceChild() method of the parent node to replace the
// original node with the new uppercase node.
var newNode = document.createTextNode(n.data.toUpperCase());
var parent = n.parentNode;
parent.replaceChild(newNode, n);
}
else {
// If the node was not a Text node, loop through its children,
// and recursively call this function on each child.
var kids = n.childNodes;
for(var i = 0; i < kids.length; i++) uppercase(kids[i]);
}
}
</script>
<!-- Here is some sample text. Note that the p tags have id attributes -->
<p id="p1">This <i>is</i> paragraph 1.</p>
<p id="p2">This <i>is</i> paragraph 2.</p>
<!-- Here is a button that invokes the uppercase() function defined above -->
<!-- Note the call to Document.getElementById() to find the desired node -->
<button onclick="uppercase(document.getElementById("p1"));">Click Me</button>
</html>