JavaScript DHTML/Development/DOM Content

Материал из Web эксперт
Перейти к: навигация, поиск

Adding/Replacing DOM Content

   <source lang="html4strict">

<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>

This is the one and only paragraph on the page.

</BODY> </HTML>


      </source>
   
  


A DOM Core Document Analyzer

   <source lang="html4strict">

<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("
    ") for(var i=0; i<children.length; ++i) { var child = children.item(i) doc.write("
  • ") getDocumentStructure(child, doc) } doc.writeln("
")
}

} </script> </head> <body onload="analyzeDocument()">

h1 center

p p code after p

second p

</body> </html>

      </source>
   
  


Check DOM Node object whether represents an HTML tag

   <source lang="html4strict">

/* 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>

<body onload="alert("This document has " + countTags(document) + " tags")"> This is a sample document. </body> </html>

      </source>
   
  


Creating a Table: Using the insertBefore Method with DOM

   <source lang="html4strict">

<HTML> <HEAD> <TITLE> Building tables using DOM </TITLE> </HEAD> <BODY ID="bodyNode"> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>

      </source>
   
  


CSS style sheet a "window" visual effect

   <source lang="html4strict">

/* 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>


Test Window

1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0

Another Window

This is another window. Its z-index puts it on top of the other one.

</body>


      </source>
   
  


Define a NodeFilter function to accept only "img" elements

   <source lang="html4strict">

/* 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

}

      </source>
   
  


If a DOM Node object is a Text object

   <source lang="html4strict">

/* 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>

<body onload="alert("Document length: " + countCharacters(document.body))">

This is a sample document.

How long is it? </body> </html> </source>

Navigating Documents

   <source lang="html4strict">

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>

      </source>
   
  


recursively looks at node n and its descendants: replacing with their uppercase equivalents

   <source lang="html4strict">

/* 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>

<p id="p1">This is paragraph 1.

This is paragraph 2.


<button onclick="uppercase(document.getElementById("p1"));">Click Me</button> </html>

      </source>