1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>GetElements Enhanced Demonstration</title>
6 <!--
7 File: D:\cssd.local\E\Student Resources\Website Development I\CodeSamples\GetElementsDemonstration-Enhanced.html
8 Copyright (c) 2022 by Jesse Heines. All rights reserved. May be freely
9 copied or excerpted for educational purposes with credit to the author.
10 updated by JMH on May 9, 2022 at 11:42 AM
11 -->
12 <script>
13 var nExample = 0 ;
14 var NextExample = function() {
15 console.log( "nExample = " + nExample )
16 switch( nExample ) {
17 case 0 :
18 // example #0 = restore the initial state
19 collectionP[1].innerHTML = "two" ;
20 collectionP[1].style.fontWeight = "normal" ;
21 var elemThree = document.getElementsByTagName( "h2" )[0] ;
22 if ( elemThree != null ) {
23 elemThree.outerHTML = "<p>three</p>" ;
24 }
25 for ( var k = 0 ; k < collectionP.length ; k++ ) {
26 collectionP[k].style.color = "black" ;
27 }
28 break ;
29
30 case 1 :
31 // example #1 = set all elements red
32 for ( var k = 0 ; k < collectionP.length ; k++ ) {
33 collectionP[k].style.color = "red" ;
34 }
35 break ;
36
37 case 2 :
38 // example #2 = set the 2nd element to "four" in blue, bold text
39 collectionP[1].innerHTML = "four" ;
40 collectionP[1].style.color = "blue" ;
41 collectionP[1].style.fontWeight = "bold" ;
42 break ;
43
44 case 3 :
45 // example #3 = change the 3rd element to a Heading 2
46 collectionP[2].outerHTML = "<h2>five</h2>" ;
47 break ;
48 }
49 nExample = ++nExample % 4 ;
50 }
51 </script>
52
53 </head>
54
55 <body>
56 <p>one</p>
57 <p>two</p>
58 <p>three</p>
59
60 <button id="btnNext" type="button" onclick="NextExample()">Next Example</button>
61
62 <script>
63 var collectionP = document.getElementsByTagName("p") ;
64 document.writeln( "<div><br><code>collectionP</code> has type <code>" +
65 typeof collectionP + "</code>.</div>" ) ;
66 document.writeln( "<div><code>collectionP</code> has " + collectionP.length +
67 " elements.</div>" ) ;
68
69 NextExample() ;
70
71 </script>
72
73 <p><br>
74 <hr></p>
75 <p><em>Important Notes:</em> (source:
76 <a href="https://www.w3schools.com/jsref/dom_obj_htmlcollection.asp"
77 target="_blank">https://www.w3schools.com/jsref/dom_obj_htmlcollection.asp</a>)</p>
78 <ul>
79 <li>An <code>HTMLCollection</code> is not an <code>Array</code>!</li>
80 <li>An <code>HTMLCollection</code> may look like an array, but it is not.</li>
81 <li>You can loop through an <code>HTMLCollection</code> and refer to its elements
82 with an index.</li>
83 <li>But you cannot use <code>Array</code> methods like <code>push()</code>,
84 <code>pop()</code>, or <code>join()</code> on an <code>HTMLCollection</code>.</li>
85 </ul>
86 </body>
87
88 </html>