To Use Getattribute(), Or Not To Use Getattribute(): That Is The Question
Solution 1:
Whenever someone recommends a practice they should always justify the advice.
Reasons for not using getAttribute and setAttribute are than IE versions up to and including 8 at least have bugs in their implementation of those DOM methods. Also, browsers have differences in how they change DOM properties in response to the use of get/setAttribute.
However, browsers are remarkably consistent in regard to DOM properties, so it is much simpler to write cross browser code if you use DOM properties. The only caveat is that some browsers do not create DOM properties for non-standard HTML attributes, but they will all set them using properties.
An added bonus is that DOM property access is much faster than using a function call to get/setAttribute.
HTML5 is attempting to standardise some of these behaviours, but the problem with HTML5 is that it is not a W3C standard (and may never be) and that it is a "living specification" that attempts to not only document what browsers do (more or less) but also what its authors would like them to do without distinguishing between the two. So while it is helpful as a kind of "as built" specification plus wish list, it is quite useless as a standard.
Edit July 2017
The W3C has been publishing HTML 5 specifications for a while now (including numbered versions and lists of changes), and the WHATWG also publishes HTML and DOM standards with almost daily updates but without indicating what has changed. One or the other may give up eventually.
Solution 2:
I use the direct property access like obj.href
when it's a standard attribute that all browsers support because I find the code a lot more readable and it works.
If it's a non-standard attribute or one I made up myself as a means of storing some data on the object, I use get/setAttribute()
.
I know of no reasons why one should always use get/setAttribute()
and I've never had trouble in any browser using obj.id
, obj.href
, obj.className
, obj.value
, etc...
Post a Comment for "To Use Getattribute(), Or Not To Use Getattribute(): That Is The Question"