Visit Mozilla.org

DOM:element.attributes

From MDC

« Gecko DOM Reference

Contents

[edit] Summary

Returns a collection of attributes of the given element.

[edit] Syntax

var attrs = element.attributes;

The returned object is of type NamedNodeMap, containing Attr nodes. If the element has no specified attributes, then the returned object has a length of 0 (zero). This attribute is read-only.

[edit] Example

// get the first <p> element in the document
var para = document.getElementsByTagName("p")[0];
var atts = para.attributes;

[edit] Notes

The items of the collection are accessible by their names and indices. Notice though, that unlike a NodeList, a NamedNodeMap doesn't maintain its items in any particular order.

You should only use access by index when enumerating over element's attributes, as in the following example, which prints the values of all the attributes of the "p1" element in the document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html>

 <head>
  <title>Attributes example</title>
  <script type="text/javascript">
   function showFirstAttr() 
   {
    var firstPara = document.getElementById("p1");
    var outputText = document.getElementById("result");

    // First, let's verify that the paragraph has some attributes    
    if (firstPara.hasAttributes()) 
    {
      var attrs = firstPara.attributes;
      var text = ""; 
      for(var i=attrs.length-1; i>=0; i--) {
        text += attrs[i].name + "->" + attrs[i].value;
      }
      outputText.value = text;
    } else {
      outputText.value = "No attributes to show"
    };
   }
  </script>
 </head>

<body>
 <p id="p1" style="color: green;">Sample Paragraph</p>
 <form action="">
  <p><input type="button" value="Show first attribute name and value"
      onclick="showFirstAttr();">
  <input id="result" type="text" value=""></p>
 </form>
</body>
</html>

While a NamedNodeMap can be iterated like an array, it doesn't have any of the special methods Array has, such as join, split, etc.

To access a specific attribute by its name, use the getAttribute method.

[edit] Specification