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");

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

So, ideally we would want to avoid using attr(). But, can we do that (for any attribute)? I believe 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:,

For anchors: foo.href,, 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