Reading elements attributes
HTML elements often contain a number of attributes with associated values:
<div id="id1" title="report">Here is some text.</div>
The attributes are always placed within the opening tag, each attribute being of the form attribute=value. The attributes themselves are child nodes of the element node in which they appear below
Having navigated to the element node of interest, you can read the value of any of its attributes using the getAttribute() method:
var myNode = document.getElementById("id1"); alert(myNode.getAttribute("title"));
The previous code snippet would display “report” within the alert dialog. If you try to retrieve the value of a nonexistent attribute, getAttribute() will return null. You can use this fact to efficiently test whether an element node has a particular attribute defined:
if(myNode.getAttribute("title")) { ... do something ... }
The if() condition will only be met if getAttribute() returns a non-null value, since null is interpreted by JavaScript as a “falsy” value (not Boolean false, but considered as such).
There also exists a property simply called attributes that contains an array of all of a node’s attributes. In theory you can access the attributes as name=value pairs in the order they appear in the HTML code, by using a numerical key; so attributes[0].name would be id and attributes[1].value would be 'report'. However, its implementation in Internet Explorer and some versions of Firefox is buggy. It’s safer to use getAttribute() instead.