Monday, April 23, 2012

Retrieving HTML attribute values "the DOM 0 way"

jQuery has an attr() method which retrieves the value of a given HTML attribute. For instance:



var foo = document.getElementById("foo");
$(foo).attr("id");


But, performance-wise this is not optimal since an jQuery object has to be created just to call the attr() method. This performs better: foo.id.



So, ideally we would want to avoid using attr(). But, can we do that (for any attribute)? I believe foo.id and foo.value is "safe" (cross-browser), but I remember having issues with foo.href.



Here is a list of various attributes that I would like to be able to retrieve "directly":



For any element: foo.id, foo.name

For anchors: foo.href, foo.target, foo.rel

For images, objects, iframes: foo.src, foo.width, foo.height

For form elements: foo.checked, foo.selected, foo.disabled, foo.readonly, foo.type, foo.value, foo.action



So the question is: Are the above expressions cross-browser? Can I use them safely?



A link to an article which examines this issue would also be nice.



Edit (based on the answers): The expressions in bold are not safe to use!





No comments:

Post a Comment