LESSON 09B – CHANGING HTML USING JAVASCRIPT
USING THE ID ATTRIBUTE
You
should get used to using the id attribute in elements that you want to access
through javascript. This will allow you
to change the attributes and content of the elements. For example, in an image, we can change the file source of the
image or we can change the border size.
For a div, we can change the text inside.
Example code
Here is how we add the id attribute
to an image. Note that no other element
on the webpage should have the same id name.
It is to be unique!
<img src="filename.jpg"
id="but01">
REFERRING TO ELEMENTS IN JAVASCRIPT
Unfortunately,
referring to the different html elements in javascript is a little messy
(although it is easy).
You need
to use the following:
document.getElementById("idName")
Example code
To refer
to the image in the previous example code, we would use:
document.getElementById("but01")
SETTING ATTRIBUTES OF ELEMENTS
We never
want to simply refer to elements. What
we want to do is change some of their attributes. Here’s the general way we do this:
document.getElementById("idName").attribute
= value;
Example code
For example, we can change the src for the image with id
name "img1" by using the following:
document.getElementById("img1").src =
"newFilename.jpg";
Example code 2
We can also change the border of the
image with id name "coco" by using the following:
document.getElementById("coco").border =
"5";
FULL EXAMPLE – CHANGING IMAGE SRC
The
following example changes the image’s src when a button is clicked.
<html>
<head>
<script type="text/javascript">
function change()
{
document.getElementById("img1").src
="sens.jpg";
}
</script>
</head>
<body>
<img src="leafs.jpg"
id="img1"><br>
<input type="button" value="Improve Image"
onClick="change()">
</body>
</html>
Click here to see it in action.
CHANGING CONTENT
We now know how to change the
attributes of an element. However, how
do we change the content of a div tag?
It turns out that the attribute
innerHTML is actually the content of the tag.
document.getElementById("idName").innerHTML
= "Whatever message you want to say.";
FULL EXAMPLE – CHANGING DIV CONTENT
The following example will change
the div’s text using three buttons.
<html>
<head>
<script
type="text/javascript">
function
change1()
{
document.getElementById("msg").innerHTML
="Mr. Campeau is very cool.";
}
function
change2()
{
document.getElementById("msg").innerHTML
="Mr. Campeau is super duper awesome.";
}
function
change3()
{
document.getElementById("msg").innerHTML
="Mr. Campeau is so smart!";
}
</script>
</head>
<body>
<div
id="msg">Click buttons to change this message.</div>
<form>
<input
type="button" value="Msg 1"
onClick="change1()">
<input
type="button" value="Msg 2"
onClick="change2()">
<input
type="button" value="Msg 3"
onClick="change3()">
</form>
</body>
</html>
Click here
to see it in action.