Why jQuery 1.9+ attr() method not deprecated?

Peter Krauss picture Peter Krauss · Feb 25, 2013 · Viewed 8.3k times · Source

Can I, a jQuery1.9+ software developer, "deprecate" the use of the attr() method in my day-by-day work?


As showed in many questions,

there are a lot of confusion about "use attr or use prop?", and, by my (developer's) view point, for all uses of attr() method, we can use prop instead:

  1. backward-compatibility: coding new software not need this;
  2. performance: John says "Accessing properties through the .attr() method will be slightly slower than accessing them directly through .prop()";
  3. Change attribute value: all can be changed by the prop(name,newvalue) method.
  4. Remove attribute: all can be removed by the removeProp(name) method.
  5. Check HTML attribute values: browser use DOM, all HTML was converted to DOM, and, if DOM affected the attr(name) method also affected. About "strong type" of prop: it is better than "html string value" (ex. "checked" vs true).
  6. Check if an attribute was defined in the "HTML original code" (supposing that method attr in your browser returns undefined if it is not)... Well, we need this in some piece of software? At forms, ".val() method is the recommended jQuery way to get or set the values of form"
  7. Cross-browser consistency: both (not only attr) are consistent methods. (it is??).

So, at this time (2013), I not see a good reason to use attr method when developing new jQuery code... But, well, this is, in other words, the question: There are a good reason to use attr method in my day-by-day tasks?

Answer

cHao picture cHao · Feb 25, 2013

.attr() is not deprecated because it's useful for what it's made for, and is the only correct way to do what it's made for (short of using each element's getAttribute function, which does the same thing...or parsing the HTML yourself). The only reason we are even having this discussion at all is because jQuery (and some old browsers (cough IE cough)) incorrectly conflated attributes and properties, and that muddling is what they apparently fixed in 1.9.

.attr() retrieves attributes, while .prop() retrieves properties. The two are different things, and always officially have been (though the DOM often has a property to correspond to an attribute). If you have a <p whatever="value">, where whatever is not an attribute the browser recognizes, you'd use .attr() to get the attribute's value. .prop() wouldn't even be able to see it in most browsers.

When you care about the resulting DOM property, use .prop(). When you care about the actual HTML attribute, use .attr(). It's not really an either/or thing; you can use both in the same code and the universe won't implode even once (assuming you've used them correctly, anyway). :) Just use the one that's suited to the job you're doing at the time, and quit trying to "deprecate" stuff that's not broken.