Element tag attributes are translated by the browser into properties of the object (the reference you've created). The DOM interface provides each element with two methods for reading and setting these attribute values:
getAttribute(string name): returns the value of the attribute specified by the name argument
setAttribute(string name, string value): adds a new attribute of the specified name and value, or sets the existing attribute to the specified value.
I often like to use a utility function to inspect an element and see the properties and methods attached to it. The inspect() function seen below uses getElementById() to retrieve a reference to the element and launch an alert box containing a list of the element properties. The string of properties and values is assembled using getAttribute() to retrieve the value of each named property.
function inspect(elm){
var str = "";
for (var i in elm){
str += i + ": " + elm.getAttribute(i) + "\n";
}
alert(str);
}
To use the inspect() function to examine a table element, simply pass the table element to the function:
Want to see it in action? Click the button to inspect the table below.
one
two
three
four
five
six
seven
eight
nine
Setting new element properties can be done with the setAttribute() method. Just pass the name and the value of the attribute you want to set. Note that both parameters must be strings, so even numeric values must be within quotes. To readjust the width of a table to 400 pixels, you can employ the following code:
var table = document.getElementById("tableMain");
table.setAttribute("width","400");
The following example uses setAttribute() and the changeSize() to assign different values to this table's WIDTH attribute.
function changeSize(px){
var table = document.getElementById("tableMain2");
table.setAttribute("width",px);
}
one
two
three
four
five
six
seven
eight
nine
If no attribute of the specified name exists for the element, setAttribute() will create a new one. There's really no inherent advantage to using setAttribute() over directly setting the value via JavaScript. The following two statements essentially accomplish the same thing:
table.setAttribute("border","2");
table.border = 2;
To prevent new attributes from being set where you don't want them, you can use the element method hasAttribute() to test for the existence of the named attribute. hasAttribute() returns either true or false depending upon whether the element possesses the attribute or not.
var table = document.getElementById("tableMain");
if (table.hasAttribute("border")){
table.setAttribute("border","2");
} else {
alert("Table has no border");
}
It should be noted that hasAttribute() is supported in Netscape 6/Mozilla, but not IE5 at the time this article was composed.