Using the attributes array instead
Sometimes you may wish to access the attributes of a HTML element generically, without naming names. For such occasions, the DOM offers a new tool- attributes.
-The attributes array
The basic idea behind the attributes array is simple- it's an object containing the name/value pair of all of a given element's attributes. Let's first list the object's four primary properties.
||The name portion of an attribute|
||The value portion of an attribute|
||The total number of attributes inside an element. In IE, the property combines BOTH user and browser defined attributes.|
||A boolean variable specifying whether an attribute is user defined or not.|
Below demonstrates invoking the attributes array and its properties:
var el=document.getElementById("myelement") el.attributes.nodeName //returns the name of the first attribute of el el.attributes.nodeValue //returns the value of the first attribute of el el.attributes.length //returns the number of attributes inside "el"
-Discrepancies in NS6+ and IE5+
What a surprise, NS and IE differ in their implementation of the attributes array! This time the company to throw a fit at is Microsoft. In NS, attributes behaves as expected, containing only attributes defined by the webmaster (either through HTML or scripting). In our beloved IE, however, the object actually holds both user and browser defined attributes. Apparently IE likes to horde a lot of its own stuff inside elements. The result is information you're interested in tossed into a sea of "gibberish."
Let's examine this discrepency in fine detail:
NS6 (not to mention common sense) registers 3 attributes inside "test", though IE "sees dead attributes", and returns 78 instead.
-The workaround- the specified property
So how do we find our needles in this haysack called attributes in IE? Yep, by using the object's specified property. Supported in both IE and NS, it returns a boolean value indicating whether the attribute in question is user defined or not. We shall use it below to correctly identify the number of attributes in the above div in both browsers:
A loop is used to cycle though all of the DIV's attributes, and when found one that's user defined, increment the counter variable. Totalattributes now returns 3 in both IE and NS.
With the attributes array in one hand, and its corresponding specified property in another, you should now be able to generically pry into any element and seek out its attributes.
One of the DOM's mission statements is to simplify matters for developers, so scripting becomes an intuitive process, less reliant on memorizing scores of syntaxes. The methods getAttribute(), setAttribute(), and removeAttribute() can be used to manipulate any attribute inside any element on the page.
- Tutorial Introduction
- Using the attributes array instead