Tuesday, November 10, 2009

wtf is an attribute ?

never quite understood the subtleties of HTML attributes. reading the DOM Level 2 Core spec and finally getting a grasp of it ... overload soup, FTL

summary:
you've got a javascript object that implements the DOM Node and Element interfaces. the object has properties, since it's javascript. the Node interface provides an array-like "attributes[]", accessed by attribute index. it's also an DOM Element which provides getAttributeNode(), accessed by attribute name. they both give an Attr, which is again a javascript object representing a DOM Node. but the object properties also provide access to the same stuff, eg an "A" tag has an 'href' property, and an 'href' attribute


a.href
javascript object property
http://localhost/#search
a.getAttribute( 'href' )
String
#search
a.getAttributeNode( 'href' )
DOM Attr
Attr( '#search' )
a.attributes[0]
DOM Attr
Attr( '#search' )

i guess the property part is implementation dependent. for common stuff like 'href' it must be pretty safe to use the property. but i've got no idea if it's actually specified anywhere. and for less common stuff, you can have a property and an attribute of the same name that have different values, eg "foo". good thing dojo provides dojo.attr()

still don't know the answer to my original question: when is it safe to add properties to a javascript object that represents a DOM Node ?


the worst part: the DOM spec is written in IDL, in which an "Attribute" is a member of an interface. so we've got Node.attributes, an IDL Attribute of the DOM's Node interface. and Attr.name, an IDL Attribute of the DOM's Attr interface, which represents an "attribute".

attributes, FTL

No comments: