By A Web Design
Our aim is to change the background color of a DIV, which must be done on click of a command button.
The id of the DIV whose paragraph font size must be changed on click of a command button is main.
<div id="main" class="main"> <p>Welcome to my web site</p> <p>We sell all the widgets you need.</p> </div> <table border="1" cellspacing="0" cellpadding="0"> <tr> <td> <input type="button" id="cmdChangeFontSize" name="cmdChangeFontSize" value="Change paragraph font size" onclick="changefontsize();" /> </td> </tr> </table>
<script type="text/javascript"> function changefontsize() { var i = ""; var paragraphs = ""; paragraphs = document.getElementsByTagName("p"); for(i=0; i<paragraphs.length; i++) { paragraphs[i].style.fontSize = '2em'; } } </script>
How the DIV’s paragraph font size is changed:
When the command button whose id is cmdChangeFontSize is clicked a user defined Javascript method changefontsize(); is invoked.
When changefontsize(); is invoked a built in Javascript method getElementsByTagName("p") is passed the name of the DIV. Hence the variable paragraphs will now hold a handle to the DIV whose id=main.
The Javascript code is contained in the function changefontsize();
In this Javascript codespec the built in function getElementsByTagName("p") is passed the HTML tag p. Since there are multiple occurrences of the HTML tag p the handle to a collection of those HTML elements in the DOM is returned and will be available in the memvar paragraphs. A collection of HMTL element is always an array.
Hence the memvar paragraph holds the handle to the HTML p tag array.
paragraphs = document.getElementsByTagName("p");
Now the content within all the <p></p> tags have to have their font size increased to 2em.
Hence we will have to loop through HTML p tags array, and for each occurrence of the HTML tag p change the content fontsize to 2em.
Since the memvar paragraphs holds the handle to the HTML p tag array paragraphs.length will return the number of records held in the HTML p tag array. Now a simple for loop is used to step through the records of the HTML p tag array and change their content font size to 2em. Take a look at the Javascript code snippet below.
for(i=0; i<paragraphs.length; i++)
{
paragraphs[i].style.fontSize = '2em';
}
<html> <head> <title>Second HTML DOM Example</title> <script type="text/javascript"> function changefontsize() { var i = ""; var paragraphs = ""; paragraphs = document.getElementsByTagName("p"); for(i=0; i<paragraphs.length; i++) { paragraphs[i].style.fontSize = '2em'; } } </script> </head> <body> <div id="main" class="main"> <p>Welcome to my web site</p> <p>We sell all the widgets you need.</p> </div> <table border="1" cellspacing="0" cellpadding="0"> <tr> <td> <input type="button" id="btn2" name="fontsize" value="Change paragraph font size" onclick="changefontsize();" /> </td> </tr> </table> </body> </html>