Monday, March 9, 2015

HTML Form Elements - Differences in attributes and properties

HTML Form elements are the staple widgets that you come across as a web developer. These are your basic button, text-input field, text area, check-box etc.
But the APIs are not as simple as they seem though, if you are seeing them new.

Lets see why..

The HTML Form elements can be updated by updating the Element attributes and the DOM object properties.

Attributes are available directly on the element
Eg:
<input id ='inputfield' type ='text' value ='foo'>
Here id, type and value are attributes

DOM properties are available via the DOM API on the Element
i.e.
var textInput = document.getElementById('inputfield')
textInput.value is a DOM property

Its nice to see that the property names are consistent with the attribute names(for the most part)

But its confusing that the behavior is not consistent.

Attribute values only represent the initial value
i.e. once a user-interaction changes the state, the attribute values are not representative of the visual,
 whereas DOM object properties can be used to update and query the current state of the element
It has always worked this way and per the spec.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-49531485

Here is a fiddle to help understand better
http://jsfiddle.net/deepakanand/sLd65egb/3/

Related bug reports (that have been marked as not bugs)
https://bugzilla.mozilla.org/show_bug.cgi?id=223003
https://bugzilla.mozilla.org/show_bug.cgi?id=327020

No comments:

Post a Comment