HTML and CSS Reference
In-Depth Information
EXAMPLE 15.3
<html>
<head><title>Working with Tags</title>
<style type="text/css">
body {background-color:aliceblue;color:green;
font-size:larger;}
h1{color:darkblue; }
</style>
</head>
<body>
1
<h1> First</h1>
<h1> Second</h1>
<h1> Third</h1>
2
<script type="text/javascript">
3
var heading1=document.getElementsByTagName("h1") ;
document.write(heading1 + "<br />");
document.write("There are "+
4
heading1.length + " H1 tags.<br />");
5
for(i=0; i< heading1.length; i++){
6
document.write( heading1[i].nodeName +": <em>"+
7
heading1[i].childNodes[0].nodeValue +"</em><br />");
}
</script>
</body>
</html>
EXPLANATION
1
Three <h1> tags are used in this document.
2
Because of the top-down processing by the HTML renderer, be sure to put the
JavaScript program at the end of the document. This way, the tags will already
have been identified before they are put into the HTML collection returned by the
getElementsByName() method.
3
The HTML collection of h1 tags is stored as an array of nodes in the variable,
heading1 .
4
The length of the array is 3 in this example because there are three H1 elements
in the document. See Figure 15.10.
5
The for loop will iterate through each of the heading1 tag objects in the HTML col-
lection.
6
The nodeName property contains the name of the HTML element.
7
The child of the h1 element, childNodes[i] , (where i is the index value) is the text
between the < h1 > tags. The nodeValue property contains the actual text.
Search WWH ::




Custom Search