For ages, I’ve been using the attr()
method to get and set the values of DOM nodes in jQuery. But I ran across a problem recently when I tried to add a pubdate
property to a time
element. Using sttr()
, I passed in {'pubdate':true}
. But this gave me a DOM node with pubdate="true"
, rather than simply giving it the property pubdate
.
Whilst I always used to keep myself very strict about using attributes like selected="selected"
and checked="checked"
, there’s really no need. Setting an input type="checkbox"
to checked
is valid. And, more importantly, it’s the property of the input that is being set.
Since version 1.6 of jQuery, the prop()
method has been available. There is a lot of crossover between the two, and very often they return the same value, but there is an important distinction. One works on the value of the attribute, the other on the property itself.
According to the spec, the attr()
method does the following:
Get the value of an attribute for the first element in the set of matched elements.
Whereas the prop()
does this:
Get the value of a property for the first element in the set of matched elements.
In all the research I’ve done (including this Stack Overflow answer) it seems that prop()
is what you need most of the time. It accesses the specific property you’re looking for, not the way in which the markup has used the attribute to specify it.
However, the attr()
method is still useful. I have found a case where I need to take the page an a
tag links to and manipulate that data. The back-end code is writing out the href
attribute, so it is controlled by the server.
When you use prop()
on an href, it gives you the full URL (e.g. http://www.example.com/link/to/page.html). But what I wanted was what the code had written as the href attribute (e.g. /link/to/page.html), so I needed to use the attr()
method.
In summary: use prop()
unless you have a very good reason for getting the exact value of an attribute.
The post What’s the difference between jQuery’s prop() and attr() methods? appeared first on chrismar.sh.