Main Page

Table methods

To get and set the
src
and
border
attributes using the Core DOM, you use the
getAttribute()
and
setAttribute()
methods:
alert(oImg.getAttribute(“src”));
alert(oImg.getAttribute(“border”));
oImg.setAttribute(“src”, “mypicture2.jpg”);
oImg.setAttribute(“border”, “1”);
However, using the HTML DOM, you can get and set these values using properties with the same name:
alert(oImg.src);
alert(oImg.border);
oImg.src = “mypicture2.jpg”;
oImg.border = “1”;
The only instance where the attribute name isn’t the same as the property name is in the
class
attribute,
which specifies a CSS class to apply to an element, such as in the following:
<div class=”header”></div>
Because
class
is a reserved word in ECMAScript, it cannot be used as a variable, property, or function
name in JavaScript. Therefore, the property is
className
:
alert(oDiv.className);
oDiv.className = “footer”;
Using properties to modify attributes instead of
getAttribute()
and
setAttribute()
affords no real
advantages aside from decreasing the code’s size and making it a little bit easier to read.
Table methods
Suppose you want to create the following HTML table using the DOM:
<table border=”1” width=”100%”> <tbody>
<tr>
<td>Cell 1,1</td>
<td>Cell 2,1</td>
</tr>
<tr>
<td>Cell 1,2</td>
<td>Cell 2,2</td>
</tr>
</tbody>
</table>
Internet Explorer has a major problem with
setAttribute()
: When you use it,
changes aren’t always reflected correctly. If you are planning on supporting Internet
Explorer, it is best to use the attribute properties as often as possible.
179
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 179


JavaScript EditorFree JavaScript Editor     Ajax Editor


©