HomeDHTML Page 7 - Rough Guide To The DOM (part 1)
Alternatives - DHTML
It's the bane of Web developers everywhere - conflicting standards, browser incompatibilities, and code that changes every time a new browser version hits the Web. But fear not - charging in on a white steed comes a heroic knight, clad in the attire of the new W3C DOM and armed with the tools to make this nightmare end forever. Read on to find out how the new DOM finally brings some standards to the decidedly non-standard world of the Web.
An alternative way of obtaining (and setting) attribute values is via theattributes[] collection, which is essentially an array containing a list ofall the attribute-value pairs for a specific tag. I've modified theprevious example to illustrate how this works - uncomment the variousalert()s to see the values of the different properties.
<html><head></head><body id="body" bgcolor="white"><font face="Arial"
size="2">This stuff is giving me a headache already!</font>
<script language="JavaScript">
// get to the <font> tag
var fontObj = document.getElementById("body").childNodes[0];
// return the number of attributes of the <font> tag
// or the length of the attributes[] collection
// returns 2
// alert(fontObj.attributes.length);
// returns the name of the first attribute - "face"
// alert(fontObj.attributes[0].name);
// returns the value of the first attribute - "Arial"
// alert(fontObj.attributes[0].value);
// changes the value of the first attribute to "Verdana"
fontObj.attributes[0].value = "Verdana";
// returns the new value of the first attribute - "Verdana"
// alert(fontObj.attributes[0].value);
</script>
</body>
</html>