Node.attributes

This article is in need of a technical review.

Since Firefox 22, Node.attributes is no longer supported (not implemented by other browsers and removed from the spec). It is only supported on Element (Element.attributes).

Summary

.attributes is a collection of all attribute nodes registered to the specified node. It is a NamedNodeMap,not an Array, so it has no Array methods and the Attr nodes' indexes may differ among browsers. To be more specific, attribute is a key value pair of strings that represents any information regarding that node; it cannot hold Object. Attribute can hold additional data/information that is required while processing custom JavaScript. There are many predefined attributes for different nodes used for binding events, validations, and specifying layout informations that are handled by browser (may vary from browser to browser).  

.attributes is dynamically updated by the browser with all inline and JavaScript-created attribute nodes.

« DOM Reference

Syntax

x=element.attributeName                    //if attributeName is a W3C defined attribute and an Attribute Node for the element (e.g., id),
                                           //   x gets assigned the value of that Attribute Node
                                           //if attributeName isn't a W3C defined attribute or an attribute node for the element,
                                           //   x gets assigned the value of the attributeName property for element (JavaScript object)

x=element.attributes.attributeName.value   // }if attributeName is an Attribute Node for the element, x gets assigned that node's value
  element.attributes['attributeName'].value// }if attributeName isn't an Attribute Node, produce EXCEPTION
  element.attributes[indexNumber].value    // }(same for indexing by indexNumber)

x= element.getAttribute('attributeName')   // if attributeName is an Attribute Node for the element, x gets assigned its value
                                           // if attributeName isn't an Attribute Node for the element, x gets assigned the null value

element.attributeName= x                   //if attributeName is a W3C defined attribute and an attribute node for the element (e.g., id),
                                           //   that Attribute Node gets assigned the value of x
                                           //if attributeName isn't a W3C defined attribute or an attribute node for the element, 
                                           //   the element's (JavaScript object) attributeName property is assigned the value of x

element.attributes.attributeName.value   =x// }if attributeName is an Attribute Node for the element, it's assigned the value of x
element.attributes['attributeName'].value  // }if attributeName isn't an Attribute Node, produce EXCEPTION
element.attributes[indexNumber].value      // }(same for indexing by indexNumber)

element.setAttribute('attributeName', x)   // Creates an Attribute Node named attributeName for the element (if one doesn't exist),
                                                  and assigns its value as x

attributeMap= element.attributes           // Assigns to attributeMap a NameNodeMap collection of Attr nodes that are copies of the
                                           // ones in the element's .attributes collection. Length is 0 if the element has no
                                           // Attribute Nodes. The element.attributes syntax is read only.
style is mirrored in the .attributes collection.
Changes to style, whatever the method, update the .attributes collection, the element's attribute nodes, and the CSSStyleDeclaration object in Firefox.
Consider quirksmode for compatibility issues in other browsers, or open the following example in your browser.

Example

<html>
<body style="white-space:nowrap">
<p id="0" onclick="checkAttributes(event)"      style="color: 000; text-indent: 10px" attrib0="value0">Click on this paragraph to show its .attributes collection and ways you can read/modify it</p>
<p id="1" onclick="alert('Paragraph1 onclick')" style="color: 000; text-indent: 10px"                 >This paragraph is similar to the one above</p>
<p id="2" onclick="alert('Paragraph2 onclick')" style="color: 000; text-indent: 10px"                 >As is this paragraph</p>
<div id="container" style="font-family: Courier New; font-size: 13px"></div>

<script>
/* This html file can be opened in all modern browsers, to help 
   highlight implementation differences regarding .attributes   */

function w(text){document.getElementById("container").innerHTML+=text}

function checkAttributes(event){
var t=[]; var ta=[]
for (var i=0;i<3;i++){t[i]=document.getElementById(i);ta[i]=t[i].attributes}
var br="<br/>"
var sp="&nbsp"
for (var i=0;i<39;i++){sp+="&nbsp"}
var te=["Directly &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp: ", "Via .attributes : ", "Via getAttribute: ", "Directly, color : ", "Directly, all &nbsp&nbsp: ", "This returns a ",  " ... gives the following results upon reading it: ", " (This syntax has signaled an error)", " (p#0's .attributes collection now contains ", " attribute nodes)", "<b><I>(IE does not change the event handler through this syntax)</I></b>", " <b><I>(Safari and Chrome don't update .attributes through this syntax)</I></b>", "<b><i> (This syntax returns a function in IE, the function's string everywhere else)</i></b>", "<b><i> (This syntax returns null in IE, the function's string everywhere else)</i></b>", "<b><i> (this syntax returns the attributes' value in IE, undefined everywhere else)</i></b>", "<b><i> (This syntax creates an attribute node for the element in IE, but in no other browser)</i></b>", "<b><i> (This syntax returns the attribute's value in IE, but in no other browser)</i></b>"]


w(".attributes is an "+ ta[0]+ ", a dynamically updated collection of the element's Attr nodes."+br)
w("Initially the paragraph you clicked on had 4 inline attributes (id, onclick, style, attrib0), and the"+br)
w(".attributes collection consisted of "+ta[0].length+" nodes. These numbers are equal in FF, Safari, Chrome, and Opera."+br)
w("IE, on the other hand, populates .attributes with all possible attributes for the element."+br+br)


w("<h4>"+"How to READ inline attributes, event handlers, and style within .attributes"+"</h4>") 
w("p#0.id      ... "+br+te[0]+ t[0].id +br+te[1]+ ta[0].id.value +br+te[2]+ t[0].getAttribute('id') +br+br)
w("p#0.onclick ... "+br+te[0]+te[5]+ typeof t[0].onclick+ " : " + t[0].onclick +br+te[1]+te[5]+ typeof ta[0].onclick.value +" : "+ ta[0].onclick.value +br+te[2]+te[5]+ typeof t[0].getAttribute('onclick') +" : "+ t[0].getAttribute('onclick') +te[12]+br+br)
w("p#0.style   ... "+br+te[3]+ t[0].style.color +br+te[4]+ t[0].style.cssText +br+te[1]+ ta[0].style.value +br+te[2]+ t[0].getAttribute('style') +br+br)
w("p#0.attrib0 ... "+br+te[0]+ t[0].attrib0 +te[14]+br+te[1]);try{t[0].attrib0.value}catch(err){w(te[7])};w(br+te[2]+ t[0].getAttribute('attrib0') +br+br)

w("<h4>"+"How to CHANGE INLINE ATTRIBUTES within .attributes and READ JAVASCRIPT-DEFINED ATTRIBUTES"+"</h4>")
                   t[0].id="ChangedId0"
w(                " p#0.id='ChangedId0'" +br+te[0]+ t[0].id +br+te[1]+ ta[0].id.value +br+te[2]+ t[0].getAttribute('id') +br+br)
            ta[1].id.value='ChangedId1'
w("p#1.attributes.id.value='ChangedId1'" +br+te[0]+ t[1].id +br+te[1]+ ta[1].id.value +br+te[2]+ t[1].getAttribute('id') +br+br)
   t[2].setAttribute('id', 'ChangedId2')
w( "p#2.setAttribute('id', 'ChangedId2')"+br+te[0]+ t[2].id +br+te[1]+ ta[2].id.value +br+te[2]+ t[2].getAttribute('id') +br+br)


w("<h4>"+"How to CHANGE INLINE EVENT HANDLERS within .attributes and READ JAVASCRIPT-DEFINED EVENT HANDLERS"+"</h4>")
          t[0].onclick=function(){alert(null)}
w(        "p#0.onclick=function(){alert(null)}"           +br+te[0]+te[5]+ typeof t[0].onclick +" : "+ t[0].onclick +br+te[1]+te[5]+ typeof ta[0].onclick.value +" : "+ ta[0].onclick.value +te[13]+br+te[2]+te[5]+ typeof t[0].getAttribute('onclick') +" : "+ t[0].getAttribute('onclick') +te[12]+br+br)
            ta[1].onclick.value='alert(false)'
w("p#1.attributes.onclick.value='alert(false)'" +br+te[10]+br+te[0]+te[5]+ typeof t[1].onclick +" : "+ t[1].onclick +br+te[1]+te[5]+ typeof ta[1].onclick.value +" : "+ ta[1].onclick.value +br+te[2]+te[5]       + typeof t[1].getAttribute('onclick') +" : "+ t[1].getAttribute('onclick') +br+br)
    t[2].setAttribute('onclick', 'alert(true)')
w(  "p#2.setAttribute('onclick', 'alert(true)')"+br+te[10]+br+te[0]+te[5]+ typeof t[2].onclick +" : "+ t[2].onclick +br+te[1]+te[5]+ typeof ta[2].onclick.value +" : "+ ta[2].onclick.value +br+te[2]+te[5]       + typeof t[2].getAttribute('onclick') +" : "+ t[2].getAttribute('onclick') +br+br)


w("<h4>"+"How to CHANGE INLINE STYLE within .attributes and READ JAVASCRIPT-DEFINED STYLE"+"</h4>")
           t[0].style.cssText='color: CCC; text-indent: 0px'
w(         "p#0.style.cssText='color: CCC; text-indent: 0px'" +br+te[11]+br+te[3]+ t[0].style.color +br+te[4]+ t[0].style.cssText +br+te[1]+ ta[0].style.value +br+te[2]+ t[0].getAttribute('style') +br+br)
        try{ta[1].style.value='color: CCC; text-indent: 1px'
w("p#1.attributes.style.value='color: CCC; text-indent: 1px'"           +br+te[3]+ t[1].style.color +br+te[4]+ t[1].style.cssText +br+te[1]+ ta[1].style.value +br+te[2]+ t[1].getAttribute('style') +br+br)}catch(er){w(te[7]+br+br+br+br+br+br)}
   t[2].setAttribute('style', 'color: CCC; text-indent: 2px')
w( "p#2.setAttribute('style', 'color: CCC; text-indent: 2px')"          +br+te[3]+ t[2].style.color +br+te[4]+ t[2].style.cssText +br+te[1]+ ta[2].style.value +br+te[2]+ t[2].getAttribute('style') +br+br)


w("<h4>"+"How to READ AN UNDEFINED ATTRIBUTE within .attributes"+"</h4>")
w(te[0]+ t[0].newattribute +br+te[1]); try{ta[0].newattribute.value}catch(er){w(te[7])};w(br+te[2]+ t[0].getAttribute('newattribute') +br+br)

w("<h4>"+"How to ADD AN ATTRIBUTE VIA JAVASCRIPT to .attributes"+"</h4>")
w(te[8]+ ta[0].length +te[9]+br)
                                 t[0].setAttribute('attrib1', 'value1')
w(                               "p#0.setAttribute('attrib1', 'value1')"                                                    +br+te[8]+ ta[0].length +te[9]+br+te[0]+ t[0].attrib1 +te[14]+br+te[1]+ ta[0].attrib1.value +br+te[2]+                        t[0].getAttribute('attrib1') +br+br)
                     temp=document.createAttribute('attrib2');temp.nodeValue='value2';t[0].setAttributeNode(temp)
w(                  "temp=document.createAttribute('attrib2');"+br+"temp.nodeValue='value2'"+br+"p#0.setAttributeNode(temp)"+br+te[8]+ ta[0].length +te[9]+br+te[0]+ t[0].attrib2 +te[14]+br+te[1]+ ta[0].attrib2.value +br+te[2]+                        t[0].getAttribute('attrib2') +br+br)
        try{ta[0].attrib3=document.createAttribute('attrib3');ta[0].attrib3.value='value3'
w("p#0.attributes.attrib3=document.createAttribute('attrib3');"+br+"p#0.attributes.attrib3.value='value3'"                  +br+te[8]+ ta[0].length +te[9]+br+te[0]+ t[0].attrib3 +br+te[1]+        ta[0].attrib3.value +br+te[2]+                        t[0].getAttribute('attrib3') +br+br)}catch(er){w(te[7]+br+br+br+br+br+br)}
                                               t[0].attrib4='value4'
w(                                             "p#0.attrib4='value4'"                                             +br+te[15]+br+te[8]+ ta[0].length +te[9]+br+te[0]+ t[0].attrib4 +br+te[1]); try{w(ta[0].attrib4.value)}catch(er){w(te[7])};w(te[16]+br+te[2]+ t[0].getAttribute('attrib4') +te[16]+br+br)
}
</script>
</body>
</html>

Notes

Numerical indexing is useful for going through all of an element's attributes.
The following example runs through the attribute nodes for the element in the document with id "p1", and prints each attribute's value.

<!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>

External links

Cross-browser compatibility considerations: on quirksmode

Document Tags and Contributors

Last updated by: teoli,