Scripting For The 6.0 Browsers
Revised January 27, 2002 | Printer-friendly version
Last Lesson | Next Lesson | Top
Part 2: Elemental Magic
getElementById() and getElementsByTagName() are used only to retrieve elements. But elements have their own set of methods which make it simpler to manipulate them with scripting.
Consider the following image tag for our next examples:
<img id="myImg" src="jabberwocky.gif" align="left" />
To retrive this element in JavaScript, we would use:
x = document.getElementById("myImg")
Now let's look at the DOM methods x has available to it:
getAttribute()
getAttribute() returns the value of the attribute you pass to it. To get the SRC value of this tag via JavaScript, we could do this:
myValue = x.getAttribute("src")
myValue would then contain the string "jabberwocky.gif."
setAttribute()
setAttribute() allows you to assign the value of the attribute you pass to it. It takes two arguments: the name of the attribute, and the value to set it to.
To change the ALIGN value of this tag from left to right, we can do this:
x.setAttribute("align","right")
removeAttribute()
removeAttribute() simply removes the attribute you pass to it. To remove the ALIGN attribute of this tag:
x.removeAttribute("align")
getElementsByTagName()
Hey, wait. Haven't we seen this before? You betcha. We orginally saw it in the document object, but every element has this method too. The difference is the document method returns all matching tags for the entire document, where the element method returns all matching tags for just that node.
Let's look at an example:
<table id="tableOne">
<tr>
<td>This is Cell One</td>
<td>This is Cell Two</td>
<td>This is Cell Three</td>
</tr>
</table>
<table id="tableTwo">
<tr>
<td>This is Cell Four</td>
<td>This is Cell Five</td>
<td>This is Cell Six</td>
</tr>
</table>
Here we have two tables, tableOne and tableTwo respectively. We can use getElementsByTagName() with the document itself to retrieve all the table cell elements on this page, like so:
x = document.getElementsByTagName("TD")
Which will return x as a collection of all six <TD> tags. But perhaps we would rather extract only the tags from tableTwo. To do this, we can first use getElementById() to retrieve the table element, then use getElementsByTagName() to retrieve only those table cells within that table element:
x = document.getElementById("tableTwo")
tableCells = x.getElementsByTagName("TD")
tableCells now becomes a collection of only the three <TD> tags contained within tableTwo.