Accessing Web Page Elements
By Stephen Bucaro
You can get access to a specific element on a webpage by assigning it a unique
id and then using the document.getElementById method to create
a reference to that element, as in the example is shown below.
<p id="accessme">You can access this text.</p>
<script language="JavaScript">
var bsize = 1;
function changeSize()
{
var textref = document.getElementsById("accessme");
if(bsize) textref.style.fontSize = "20px";
else textref.style.fontSize = "12px";
bsize = !bsize;
}
</script>
<input type="button" value="Change Text Size"
onclick="changeSize()"></input>
The example above changes the size of the text in the paragraph when you click
on the button.
You may not
be familiar with just creating a free-standing button that is not associated with a form.
Actually, by default, it is associated with form[0] in the document's forms
collection (assuming it's the first form on the webpage).
To access all elements of a certain type on a webpage, use the getElementsByTagName
method to create a reference to the collection of all the elements of that
type on the webpage, as in the example is shown below.
<p>You can access this text.</p>
<p>And this text.</p>
<p>And any other text in a paragraph.</p>
<script language="JavaScript">
var bsize = 1;
function changeSize()
{
var coltext = document.getElementsByTagName("p");
for(var i = 0; i < coltext.length; i++)
{
if(bsize) coltext[i].style.fontSize = "20px";
else coltext[i].style.fontSize = "12px";
}
bsize = !bsize;
}
</script>
<input type="button" value="Change Text Size"
onclick="changeSize()"></input>
The example above changes the size of the text in all paragraphs when you click
on the button.
|