-1

(Note: While it may be tempting to say this is a duplicate of .prop() vs .attr(), I do not believe it is. That post does a fantastic job explaining the difference between .prop() and .attr() but does not state definitively when one is preferable over the other, which is what this question aims to do.)

Despite having read a number of questions/answers on StackOverflow regarding the differences between .prop() and .attr(), I still see a lot of confusion on this issue.

I feel it would be useful to have a definitive reference on StackOverflow delineating when one method is preferable to the other, so that we can eliminate the guesswork and attempts at trying to figure out whether something is an attribute or a property.

Thus, I ask, for which attributes/properties is it preferable to use .prop() and for which .attr()?

Community
  • 1
  • 1
Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
  • 2
    Find your answer here http://stackoverflow.com/questions/5874652/prop-vs-attr[enter link description here][1]. [1]: http://stackoverflow.com/questions/5874652/prop-vs-attr – AzAh May 20 '13 at 17:02
  • 2
    @AzAh Did you not read the note with which he opened his question? – ajp15243 May 20 '13 at 17:03
  • 2
    @PalashMondal, yes, I included the link to the jQuery reference at the end of my answer. The point is to have the reference easily searchable on StackOverflow. – Derek Henderson May 20 '13 at 17:06
  • Yeah, I have been really confused with the question is **ID** an attribute or property??? Finally all doubts clear :) – palaѕн May 20 '13 at 17:07
  • 2
    but... how does that other question NOT explain it? it is preferable to use `.attr()` when you want the **attribute**, and `.prop` when you want the **property**. That other question defines that pretty well. – Kevin B May 20 '13 at 17:08
  • 1
    @KevinB, yet I still see a lot of confusion despite that post. For a lot of us, it's not always clear when something is a property or an attribute, despite having read that post. This question/answer was inspired by a lengthy discussion in an answer to another question. – Derek Henderson May 20 '13 at 17:10
  • @ajp15243 The fact that OP does not believe it is a duplicate does not mean it's true. Also, http://api.jquery.com/prop/ does a perfectly good job of answering the question. – Blazemonger May 20 '13 at 17:10
  • Even given the list by Derek, there are several properties there i wouldn't use .prop or .attr on. for example, the id/src is always available directly on the element cross-browser. `$("#myel")[0].id` `$("#myimg")[0].src`. I would consider needing the attribute instead of the property very rare. – Kevin B May 20 '13 at 17:13
  • @Blazemonger AzAh didn't attempt to point that out, s/he merely linked the other question with hardly any explanation. Does the other question contain sufficient information? Perhaps, but I don't think AzAh sufficiently pointed that out. – ajp15243 May 20 '13 at 17:14
  • My rule of thumb is simple, if I can do `element.property`, like with `element.id`, I use `prop()`, if it's an actual attribute, like getting the `href` attribute as typed in the HTML, I use `attr()`, if I'm trying to get the href property instead, I use `prop()` (and they are not always the same). In other words, `prop()` for properties and `attr()` for attributes. – adeneo May 20 '13 at 17:16
  • @Blazemonger, clearly you feel this question is a duplicate. However, while that question explains the differences between the two methods, it doesn't provide a clearcut list of when to use which, which continues to be a source of confusion. – Derek Henderson May 20 '13 at 17:16
  • There may be special cases when you *want* to use `.attr` even though `.prop` is a better choice in *most* cases. Rare, but conceivable. In many cases, the two are equivalent, leading to the confusion. Your question should be: "Which method should I use *in this specific case?*" – Blazemonger May 20 '13 at 17:24

2 Answers2

8

Applicable before jQuery 1.9

Below is a list of some attributes and properties and which method should normally be used when getting or setting them. This is the preferred usage, but the .attr() method will work in all cases.

+------------------------------------+------------+-----------+
| Attribute/Property                 |  .attr()   |  .prop()  |
+------------------------------------+------------+-----------+
| accesskey                          |    ✓       |           |
| align                              |    ✓       |           |
| async                              |            |    ✓      |
| autofocus                          |            |    ✓      |
| checked                            |            |    ✓      |
| class                              |    ✓       |           |
| contenteditable                    |    ✓       |           |
| disabled                           |            |    ✓      |
| draggable                          |    ✓       |           |
| href                               |    ✓       |           |
| id                                 |    ✓       |           |
| label                              |    ✓       |           |
| location (i.e., window.location)   |            |    ✓      |
| multiple                           |            |    ✓      |
| readOnly                           |            |    ✓      |
| rel                                |    ✓       |           |
| selected                           |            |    ✓      |
| src                                |    ✓       |           |
| tabindex                           |    ✓       |           |
| title                              |    ✓       |           |
| type                               |    ✓       |           |
| width (if needed over .width())    |    ✓       |           |
+------------------------------------+------------+-----------+

Neither .attr() nor .prop() should be used for getting/setting value. Use the .val() method instead (although using .attr(“value”, “somevalue”) will work.

Summary: The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

Reference

jonathanm
  • 170
  • 1
  • 3
  • 8
Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
  • 2
    _but the `.attr()` method will work in all cases._ No. – Ram May 20 '13 at 17:11
  • @undefined, I'm quoting from jQuery documentation. – Derek Henderson May 20 '13 at 17:11
  • Yes, this is true only in jQuery 1.6. – Ram May 20 '13 at 17:13
  • 1
    jQuery 1.6.1 made .attr backward compatible (it wasn't in 1.6), and 1.9 goes back to a setup similar to 1.6 where it is less backward compatible again, making .attr not work properly with some boolean properties. – Kevin B May 20 '13 at 17:14
  • `async`? Why would you ever want to change the ` – Blazemonger May 20 '13 at 17:14
  • never tried it, as it seems just wrong, but I suppose `$(window).prop('location')` should work. Anyway, this answer seems to have a lot of strange examples, and I would use prop() for src, title, type, id and several others ? – adeneo May 20 '13 at 17:18
  • The reference that you linked to is not completely applicable to the latest version of jQuery. `.attr("checked")` and `.removeAttr("checked")` will not work properly in the latest version. It may appear to work at first, but using it more than once or twice will result in it no longer working. – Kevin B May 20 '13 at 17:21
  • @adeneo `$(window).prop('location')` returns the same object that `window.location` does, not a string. While it works, I would never consider it a suitable use of the method. – Blazemonger May 20 '13 at 17:22
  • 1
    @KevinB, I will seek more references in order to provide a better answer. Any help is appreciated. (And I think this supports my contention that there is enough uncertainty about this that it would be useful to have the answer clearly stated somewhere easy to find.) – Derek Henderson May 20 '13 at 17:22
0

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

Concerning boolean attributes, consider a DOM element defined by the HTML markup , and assume it is in a JavaScript variable named elem:

elem.checked true (Boolean) Will change with checkbox state $(elem).prop("checked") true (Boolean) Will change with checkbox state

elem.getAttribute("checked") "checked" (String) Initial state of the checkbox; does not change $(elem).attr("checked") (1.6) "checked" (String) Initial state of the checkbox; does not change

$(elem).attr("checked") (1.6.1+) "checked" (String) Will change with checkbox state $(elem).attr("checked") (pre-1.6) true (Boolean) Changed with checkbox state

SOURCE

rahul maindargi
  • 5,359
  • 2
  • 16
  • 23