Приглашаем посетить
Литература (lit-info.ru)

11.2 The collection features provided by the DOM

Table of Contents

Previous Next

11.2 The collection features provided by the DOM

11.2.1 Collecting page elements by name

The getElementsByName() is our first function to collect and to gain access to a group of elements. We have used it in previous chapters and it is time now to study it in more detail from a data structure point of view. The formal declaration of the getElementsByName() function is



NodeList getElementsByName(DOMString elementName)

This function takes a string elementName as argument and searches the entire document. It returns a collection of elements that matches the elementName. To use this function, you need to understand the return type NodeList. The type NodeList is actually an object with data and functions. The definition of NodeList is given by the interface



interface NodeList {
  Node  item(in unsigned long index);
  readonly attribute unsigned long    length;
};

This object contains one read-only value length to indicate the number of returned elements in the collection. The member function item(index) is used to locate a specific element in the collection. This item() function has a return type as Node. This is a complicated object inside the DOM and not all browsers implement it fully. It has more than 10 properties and a number of associated functions. We are interested in two of the properties at this moment, namely, firstChild and data. The firstChild property is also a node and will lead us to the element itself and its related data. The data return the string of text under the element. One simple example should clarify these issues. The concept of NodeList and Node is important for the understanding of the data structure and the use of the DOM tree. We will walk through the DOM tree together later in this chapter. First, consider a simple example to use getElementsByName(), NodeList, and Node interfaces.

Suppose you have the Web page below:



Example: ex11-01.htm - Grouping Elements By Name

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title>Grouping Elements By Name -- ex1101.htm</title></head>
 6:  <style>
 7:   .butSt{background-color:#dddddd;font-family:arial;font-weight:bold;
 8:      font-size:14pt;color:#880000;width:220px;height:35px}
 9:  </style>
10:  <body style="background:#000088;font-family:arial;font-size:22pt;
11:     color:#ffff00;font-weight:bold;text-align:center">
12:   Grouping Page Elements By Name <br/>Some Blinking Paragraphs<br /><br />
13:
14:  <div name="pa" id="pa" style="color:#ffffff">This is paragraph one</div>
15:  <div name="pa" id="pa" style="color:#ffff00">This is paragraph two</div>
16:  <div name="pa" id="pa" style="color:#ff0000">This is paragraph three</div>
17:  <div name="pa" id="pa" style="color:#00ff00">This is paragraph four</div>
18:     <br /><br />
19:  <input type="button" onclick="myBlink()" class="butSt"
20:    value="Blinking Paragraphs">
21:  <input type="button" onclick="myToUpper()" class="butSt"
22:    value="To Upper Case">
23:
24:  <script src="ex11-01.js"></script>
25:  </body>
26:  </html>

This page contains four paragraphs as indicated in lines 1417. They are all defined by a division element with the same name and identity, "pa." Soon after the paragraphs, there are two buttons. The first button calls the function myBlink() to change the color of all paragraphs randomly. The effect of this is very much like blinking. The second button is used to change all paragraphs to upper case.

This simple example shows how to use grouping to utilize the special effect "blinking." Some screen shots of this example in action are shown in Figs 11.2 and 11.3.

Figure 11.2. ex11-01.htm

graphics/11fig02.jpg


Figure 11.3. Blinking paragraphs

graphics/11fig03.jpg


The external program file ex11-01.js of this example is listed below.



Example: ex11-01.js - The ECMAScript For ex1101.htm

 1:
 2: colorArr = new Array("#ff0000","#00ff00","#0000ff","#ffffff","#ffff00")
 3: function myBlink()
 4: {
 5:   llV = document.getElementsByName("pa")
 6:   noPar = llV.length
 7:   for(jj=0;jj<noPar;jj++)
 8:   {
 9:    llV.item(jj).style.color=colorArr[Math.round(Math.random()*4)]
10:   }
11:   setTimeout("myBlink()",200)
12:
13: }
14:
15:  function myToUpper()
16:  {
17:   llV = document.getElementsByName("pa")
18:   noPar = llV.length
19:   for (jj=0;jj<noPar;jj++)
20:   {
21:     llSt = llV.item(jj).firstChild.data
22:     llSt = llSt.toUpperCase()
23:     llV.item(jj).firstChild.data = llSt
24:   }
25:  }

In line 2, an array is used to specify the color for the paragraph blinking. When the Blinking Paragraphs button is clicked, the myBlink() function is called. The first statement of this function in line 5 is



llV = document.getElementsByName("pa")

This statement collects all elements with name="pa" and returns them as a collection to variable llV. Variable llV is actually a NodeList so that the property length and function item() can be called from llV. The statement in line 6 uses llV.length to represent the number of items in the collection. The for-loop in lines 710 changes the color of all paragraphs randomly. The object llV.item(jj) represents the jjth object in the collection and the style.color is then legal to change the paragraph's color.

The other button activates the myToUpper() function. After the collection of elements, the string llSt in line 21



llSt = llV.item(jj).firstChild.data

stores the text data of the jjth object. The firstChild element can be considered as the first node from the object llV.item(jj) and the data return the text. Since llSt is a string, the string function toUpperCase() will change the paragraph to upper case. The resultant string is then put back into the paragraph in line 23. Grouping elements by name is a handy technique for manipulating a number of objects as well as performing some special effects.

Sometimes, the item() function is integrated into the object and works as an array structure. For example, llV.item(jj) can also be written as llV[jj].

11.2.2 Using collections provided by the DOM

Even before the W3C standard, most browsers had their own DOM and accessing methods for page elements. For example, if you declare an image element as



<img src="myPic.gif" alt="pic" id="myPic" name="myPic" />

you can access this image and change the picture by using the following statement:



<script>
  document.myPic.src = "myNewPic.gif"
</script>

Here document.myPic is a property of the DOM (but not the W3C DOM) and can be used to manipulate the attributes of the associated elements of some browsers. A large number of pages on the Web still use this naming access method. To group elements in these formats requires special design of element names and identities.

Since element grouping is an important subject on the Web, the W3C DOM provides a number of specially designed structures to use them. The method document.getElementsByName() is the first one. Another one is to use the HTMLCollection type provided by the DOM interface. For some important elements such as images, applets, links, forms, and anchors, W3C provides standard interfaces to group them together as a special collection. Consider the definitions in lines 711 of ex11-02.txt:



readonly attribute HTMLCollection  images;
readonly attribute HTMLCollection  applets;
readonly attribute HTMLCollection  links;
readonly attribute HTMLCollection  forms;
readonly attribute HTMLCollection  anchors;

For every image element used in a page, the document.images object is a collection of them so that we can control them more easily. The formal definition of the HTMLCollection is provided by the following interface:



interface HTMLCollection {
  readonly attribute unsigned long    length;
  Node               item(in unsigned long index);
  Node               namedItem(in DOMString name);
};

This specification is similar to NodeList with length and function item(). For example, suppose you have two image elements defined in a page such as



<img src="myPic01.gif" />
<img src="myPic02.gif" />

You can change the resource of the images to a new image, myNewPic01.gif, by executing the following statements:



<script> document.images.item(0).src ="myNewPic01.gif"
         document.images.item(1).src ="myNewPic01.gif" </script>

This grouping feature provides a convenient way of performing special effects on a wide variety of applications. As a practical example, consider a ghost that appears randomly in a pyramid. The interface part of this example is given below:



Example: ex11-02.htm - Grouping By Collections

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title>Grouping By Collections  ex1102.htm</title></head>
 6:  <style>
 7:   .butSt{background-color:#dddddd;font-family:arial;font-weight:bold;
 8:      font-size:14pt;color:#880000;width:220px;height:35px}
 9:  </style>
10:  <body style="background:#000088;font-family:arial;font-size:22pt;
11:     color:#ffff00;font-weight:bold;text-align:center">
12:  DOM: The Image Collection<br />Random Ghosts In A Pyramid<br /><br />
13:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" /><br />
14:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
15:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" /><br />
16:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
17:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
18:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" /><br />
19:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
20:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
21:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
22:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
23:         <br /><br />
24:  <input type="button" onclick="myStart()" class="butSt" value="Start">
25:  <input type="button" onclick="myStop()" class="butSt" value="Stop">
26:  </body>
27:  <script src="ex11-02.js"></script>
28: </html>

Lines 1322 define10 images arranged in a pyramid shape. All these images have an initial picture cover.jpg. When the Start button is clicked, a ghost appears in the image element randomly. When the Stop button is clicked, the ghost disappears. Without using the standard image collection technique, to perform such animation we will need some sort of special design of the image element names and identity. With the collection technique, however, putting the ghost into random locations of the pyramid is much simpler. The file ex11-02.js is the program to do this task:



Example: ex11-02.js - The ECMAScript For ex1102.htm

 1:  var noImage = 9
 2:  var rImg = 0
 3:  var imgPic01 = true
 4:  var startV = true
 5:  function myImg()
 6:  {
 7:    noImg = document.images.length
 8:    document.images.item(rImg).src = "cover.jpg"
 9:    rImg = 0
10:    rImg = Math.round(Math.random()*noImage)
11:   if (startV) {
12:     if (imgPic01) {
13:        document.images.item(rImg).src = "ghost_l.gif"
14:        imgPic01 = false
15:     } else {
16:        document.images.item(rImg).src = "ghost_r.gif"
17:        imgPic01 = true
18:     }
19:     setTimeout("myImg()",300)
20:   }
21:  }
22:
23:  function myStart()
24:  {
25:    startV = true
26:    myImg()
27:  }
28:  function myStop()
29:  {
30:    startV = false
31:  }

The myStart() and myStop() functions are simple. When the variable startV equals true, the action starts by calling the function myImg() in line 26. The myStop() function sets the startV variable to false so that no further action is performed. The important function is myImg(). First, the document.images.length stores the number of image elements inside the page. The statement in line 10 generates a random number from 0 to noImage (number of images). If the starting variables startV and imagePic01 are true, you set the random image element's resource file as ghost_l.gif. If the imgPic01 is not true, you change to another ghost picture by providing an alternative picture file in line 16. As a result, you have two ghost pictures appearing on the pyramid. The setTimout() function in line 19 is used to control the speed of the program. Some screen shots of this example are shown in Figs 11.4 and 11.5.

Figure 11.4. ex11-02.htm

graphics/11fig04.jpg


Figure 11.5. Ghost in a pyramid

graphics/11fig05.jpg


Another important collection function is the document.form. Any elements declared inside the form element <form> are collected into the form collection so that you can access and control them just like using arrays. The form and its collection play a major role in the development of the Web, particularly when communication with the server is needed. A typical form element and a simple calling format may look like this:



<form action="myProgram.xxx" method="post">
  < .. .. some elements ..may be a button>
  < .. .. some elements ..may be a select box>
  < .. .. some elements ..may be an image>
  < .. .. some elements ..may be a checkbox>
 <input type="submit" value="Submit">
</form>

When the Submit button is pressed, all the data inside the form are collected and passed to the server program "myProgram.xxx." Here myProgram.xxx can be a "Program Extract Report Language" (Perl), "PHP: Hyper Preprocessor" (PHP), "Active Server Page" (ASP), or any other executable program on the server. This "client and server" communication link creates an exciting new application field on the Web, which forms the basis for database and e-commerce applications. We will discuss the server and its related database in more detail in Part IV.

To understand how forms can be used to collect page elements, let's look at an example similar to ex11-02.htm. We add a tag name <form> before the first image element as indicated in the following page fragment and call this example ex11-03.htm. This page calls a modified script program ex11-03.js which is similar to line 27 in ex11-02.htm.



Listing: ex11-03.txt - Page Fragment For ex1103.htm

 1:  <form action="">
 2:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" /><br />
 3:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
 4:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" /><br />
 5:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
 6:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
 7:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" /><br />
 8:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
 9:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
10:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
11:  <img src="cover.jpg" alt="pic" style="width:100px;height:100px" />
12: </form>

Now, all the images are embedded in the form collection (lines 1 to 12) and the statement

document.form.item(0).src or document.form[0].src

represents the resource or the picture file of the first image in line 2. In order to perform the same action as that in ex11-02.htm, all you have to do is to modify the function myImg() in ex11-02.js to use the form. The modified function myImg() in the program file ex11-03.js is listed as follows:



Listing: ex11-04.txt - The Modified myImg() Function In ex1103.js

 1:  function myImg()
 2:  {
 3:    noImg = document.form.length
 4:    document.images.item(rImg).src = "cover.jpg"
 5:    rImg = 0
 6:    rImg = Math.round(Math.random()*noImage)
 7:   if (startV) {
 8:     if (imgPic01) {
 9:        document.form.item(rImg).src = "ghost_l.gif"
10:        imgPic01 = false
11:     } else {
12:        document.form.item(rImg).src = "ghost_r.gif"
13:        imgPic01 = true
14:     }
15:     setTimeout("myImg()",300)
16:   }
17:  }

By comparing this function with that listed in ex11-02.js, you can see that only a simple replacement from "images" to "form" is required to do the job. The beauty of the element collection is that complicated operations involving a group of elements can be done in a much simpler way. To demonstrate this, we modify this example into a game.

11.2.3 A page to catch random ghosts

To transform ex11-02.htm into a simple game, you use the same interface to draw the pyramid and some ghost pictures. The rules of the game are simple. When the game starts, a ghost appear randomly in the pyramid. You use the mouse to click on the ghost. If the mouse hits the ghost, the number of hits on the scoreboard will be increased by 1. Otherwise the number of misses on the scoreboard will be increased by 1. The game is over when a total of five misses is recorded. The interface part of this example is listed in ex11-04.htm.



Example: ex11-04.htm - Catch Some Ghosts

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Catch Some Ghosts -- ex1104.htm</title></head>
 6:  <style>
 7:   .butSt{background-color:#dddddd;font-family:arial;font-weight:bold;
 8:      font-size:18pt;color:#880000;width:220px;height:35px}
 9:  </style>
10:  <body style="background:#000088;font-family:arial;font-size:22pt;
11:     color:#ffff00;font-weight:bold;text-align:center">
12:  Application Of Image Collection<br />Catch Random Ghosts<br /><br />
13:
14:  <div id="showPyramid"></div><br />
15:
16:  <div style="position:absolute;top:80px;left:130px;font-size:16pt">
17:    <span>No. Of Hits</span><br /><input type="text" readonly value="0"
18:          class="butSt" style="width:100px" id="hitId" /><br /><br />
19:    <span>No. Of Misses</span><br /><input type="text" readonly value="0"
20:          class="butSt" style="width:100px" id="missId"/>
21:  </div>
22:
23:  <input type="button" onclick="myStart()" class="butSt"
24:      value="Start" id="startId">
25:  <input type="button" onclick="myStop()" class="butSt" value="Stop">
26:  <br /><br /> <div id="outMsg"></div>
27:
28: </body>
29:  <script src="ex11-04.js"></script>
30: </html>

To enhance the reusability of programming codes, the pyramids are generated by a program and displayed in a location with id="showPyramid" as shown in line 14. Lines 1621 generate the scoreboard. The numbers of hits and misses are displayed inside the read-only text fields specified in lines 1720. There are two buttons to control the process: the Start button to start the game and the Stop button to stop at any time. The game is over when a total of five misses is reached. In this case the Start button will be disabled and the color changed to gray. Some screen shots of this example are shown in Figs 11.6 and 11.7.

Figure 11.6. ex11-04.htm

graphics/11fig06.jpg


Figure 11.7. Game over

graphics/11fig07.jpg


One interesting feature this example is that you can change the number of rows of the pyramid just by changing one parameter inside the program. The first part of the file ex11-04.js is responsible for generating the pyramids.



Example: ex11-04.js - The ECMAScript For ex1104.htm (Part One)

 1:
 2: var noHit = 0
 3: var noMiss =0
 4: var noRows = 4
 5: var speedV = 500
 6:
 7: function initPar()
 8: {
 9:  noPic = 0
10:  noHit = 0
11:  noMiss =0
12:  lSt = ""
13:  for (jj=0;jj<noRows;jj++)
14:  {
15:   for(kk=0;kk<=jj;kk++)
16:   {
17:   lSt = lSt +"<img src=\"cover.jpg\" alt=\"pic\" "+
18:      "style=\"width:100px;height:100px\" vspace=\"3\" "+
19:      "hspace=\"3\" onclick=\"myHit("+noPic+ ")\" />"
20:   noPic++
21:   }
22:   lSt = lSt + "<br />"
23:  }
24:  document.getElementById("hitId").value = noHit
25:  document.getElementById("missId").value = noMiss
26:  document.getElementById("showPyramid").innerHTML=lSt
27: }
28: initPar()
29:

The function initPar() (initial parameter) initializes the game and generates the pyramid shapes for the ghost to appear. One benefit of generating XHTML by using an external program is that you can change the number of rows and the controlling speed. The variables in lines 4 and 5 are



noRows = 4 and speedV = 500

and any changes of these values will result in changes of the shape and/or the speed of the ghost in the pyramid. You can build some select boxes to use these properties and to add more functionality to the page. The two for-loops (lines 1323) generate four rows of image elements. There are a total of 10 pictures in the following format:



<img src="cover.jpg" alt="pic" style="width:100px;height:100px"
     vspace="3" hspace="3" onclick="myHit(0)" /><br />
<img src="cover.jpg" alt="pic" style="width:100px;height:100px"
     vspace="3" hspace="3" onclick="myHit(1)" /><br />
   ...      ... ...
<img src="cover.jpg" alt="pic" style="width:100px;height:100px"
     vspace="3" hspace="3" onclick="myHit(9)" /><br />

Once you have defined these images, the scoreboard is initialized and the string lSt is displayed on the screen by executing the statement in line 26. The second part of this program file is listed below.



Listing: Continuation Of The ECMAScript ex1104.js (Part Two)

30: var rImg = 0
31: var imgPic01 = true
32: var startV = true
33: var llSt = ""
34:
35: function myImg()
36: {
37:  if (startV) {
38:    noImg = document.images.length
39:    document.images.item(rImg).src = "cover.jpg"
40:    rImg = 0
41:    totPics = (noRows * (noRows +1))/2 1
42:    rImg = Math.round(Math.random()* totPics)
43:    if (imgPic01) {
44:       document.images.item(rImg).src = "ghost_l.gif"
45:       imgPic01 = false
46:    } else {
47:       document.images.item(rImg).src = "ghost_r.gif"
48:       imgPic01 = true
49:    }
50:    setTimeout("myImg()",speedV)
51:  }
52: }
53:
54: function myStart()
55: {
56:   startV = true
57:   myImg()
58: }
59:
60: function myStop()
61: {
62:   startV = false
63: }
64:

The main function in this part is myImg() and is similar to the previous example. It generates the random appearance of the ghost. Since you have the number of rows as variable, you need to calculate how many pictures there are in total on the screen. The formulas can easily be constructed as follows:

1 row = 1 picture

2 rows = 3 pictures

3 rows = 6 pictures

k rows = k * (k+1)/2 pictures

This formula is used in line 41 to calculate the number of pictures in the game. This number is subsequently used to generate random appearances. The 1 at the end of line 41 indicates that you start the counting from 0. The speed variable speedV is used in line 50 to control the speed of motion. The higher the value of speedV, the faster the motion.

When the Stop button is pressed, the myStop() function is called to set the start variable startV to false so that no motion is allowed. Similarly, when the Start button is clicked, the myStart() function sets startV to true and executes the function myImg() to start the game.

The final part of the program contains some process functions to perform "hit the target" operations and is given below.



Listing: Continuation Of The ECMAScript ex1104.js (Part Three)

65: function displayHit()
66: {
67:   document.getElementById("hitId").value = noHit
68:   document.getElementById("missId").value = noMiss
69:   document.getElementById("outMsg").innerHTML = llSt
70:   startV = true
71: }
72:
73: function gameOver()
74: {
75:  startV = false
76:  document.getElementById("startId").disabled=true
77:  document.getElementById("startId").style.color="#888888"
78:  document.getElementById("hitId").value = noHit
79:  document.getElementById("missId").value = noMiss
80:  document.getElementById("outMsg").innerHTML = "Game Over"
81: }
82:
83: function myHit(hitV)
84: {
85:  if (startV)
86:  {
87:   startV = false
88:   if (hitV == rImg) {
89:     llSt = "You Have Hit The Target"
90:     noHit++
91:   } else {
92:     llSt = "You Have Missed The Target"
93:     noMiss++
94:   }
95:   if ( noMiss < 5) displayHit()
96:   else gameOver()
97:  }
98: }

When one of the pictures is hit, the myHit(hitV) function is activated. For example, if you hit the first image in the second row, the function myHit(1) is called. Since the rImg variable stores the current position of the ghost display, a simple comparison between hitV (hit variable) and rImg can determine whether you have caught the ghost. If the target is hit, the variable noHit (number of hits) is increased by 1. The message "You Have Hit The Target" is assigned to the string variable llSt to be displayed later. Similarly, if the target is missed, the noMiss (number of misses) is increased by 1. If the total number of misses is less than 5, the function displayHit() is called to display the result. Otherwise, the function gameOver() is called to indicate that the game is now finished. In the latter situation, the value of the variable startV is set to false to stop the game. Also, the Start button is disabled and the color changed to gray immediately. The message "Game Over" is output to the display area. In this example, it can be clearly seen that the collection of page elements makes the task of Web page design, manipulation, and programming much easier.

11.2.4 Collecting page elements by tag name

To use the function getElementsByName(), you need to assign names to each element. This has to be done at the design level. The internal collection feature provided by the DOM only applies to a handful of elements such as images, forms, applets, etc. Another, more general, element collection feature provided by the DOM is the function getElementsByTagName(). Since tag names are identical to elements in the XHTML language, this function can be used to group any elements without any restrictions.

To demonstrate this function, consider a simple page with some division <div>, image <img>, and input <input> elements. Three input elements as buttons are used. If any one of the buttons is clicked, all tag names with the associated elements are collected and the number is displayed on the screen. You can input the tag name as an argument and therefore only one user function is needed in the example. This page is listed in ex11-05.htm.



Example: ex11-05.htm - Grouping Elements By Tag Name

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title>Grouping Elements By Tag Name  ex1105.htm</title></head>
 6:  <style>
 7:   .butSt{background-color:#dddddd;font-family:arial;font-weight:bold;
 8:      font-size:14pt;color:#880000;width:150px;height:35px}
 9:  </style>
10:  <body style="background:#000088;font-family:arial;font-size:22pt;
11:     color:#ffff00;font-weight:bold;text-align:center">
12:   Grouping Page Elements By Tag Name<br /><br />
13:
14:  <div style="color:#ffffff">This is paragraph one</div>
15:  <div style="color:#ffff00">This is paragraph two</div>
16:  <div style="color:#ff0000">This is paragraph three</div>
17:  <div style="color:#00ff00">This is paragraph four</div>
18:  <img src="picUp.gif" alt="pic" width="100" height="100" />
19:  <img src="picRight.gif" alt="pic" width="100" height="100" />
20:  <img src="picDown.gif" alt="pic" width="100" height="100" />
21:  <img src="picLeft.gif" alt="pic" width="100" height="100" />
22:     <br /><br />
23:  <input type="button" onclick="groupE('div')" class="butSt"
24:      value="Grouping div " />
25:  <input type="button" onclick="groupE('img')" class="butSt"
26:     value="Grouping Img" />
27:  <input type="button" onclick="groupE('input')" class="butSt"
28:     value="Grouping Input" />
29:  <br /><br /><div id="outMsg"></div>
30:  <script>
31:  function groupE(stV)
32:  {
33:    llSt = ""
34:    divV = document.getElementsByTagName(stV)
35:    llSt = "There are "+divV.length+" &lt;"+stV+"&gt; elements <br />"
36:    document.getElementById("outMsg").innerHTML = llSt
37:  }
38: </script>
39:  </body>
40:  </html>

There are five divisions, four images, and three input elements in this page. If the first button defined in lines 2324 is clicked, the function groupE(div) is called. This function executes the statement



divV = document.getElementsByTagName(stV)

with stV="div". All elements with the name "div" are collected and returned as a collection to variable divV. This divV is a collection and therefore divV.length stores the number of items in the collection set. A string variable llSt is constructed to show the collection on the screen. In order to display the word <div>, we use the expression &lt;div&gt; as illustrated in line 35. Some screen shots of this example are shown in Figs 11.8 and 11.9.

Figure 11.8. ex11-05.htm

graphics/11fig08.jpg


Figure 11.9. Counting the elements

graphics/11fig09.jpg


    Table of Contents

    Previous Next