28

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?

Community
  • 1
  • 1
Peter Krauss
  • 11,340
  • 17
  • 129
  • 247
  • 2) You don't do that anyway 3) no 4) no 5) DOM still distinguishes attributes from properties 6) You never need to [get the page source](http://stackoverflow.com/a/3905503/1048572) – Bergi Feb 25 '13 at 20:34
  • Does none of the answers fully answer your question? I'd say that some of them are acceptable. – Joel Peltonen Dec 17 '13 at 09:32
  • Sorry, I think the answers of [prop-vs-attr](http://stackoverflow.com/questions/5874652/prop-vs-attr) was duplicated, and people not see the focus of the question (is about [best pratices](https://en.wikipedia.org/wiki/Best_practice) not the *prop-vs-attr* concepts)... As you suggested, now I click at "acceptd answer", but not like to vote my answer, especially if it not received votes. – Peter Krauss Dec 17 '13 at 09:45
  • I see now (2014) that this question received a lot of pageviews (!), but I did not expressed in a single question-phrase, *to differentiate it from the cited similar questions/answers*... So, trying to express: "Can we draw a **rule of thumb for `attr` vs `prop` most commom DOM-use?**", or "What is the **most frequent DOM-use?**"... And, sorry, perhaps because of my "express-less", or bad english: only I posted [here an direct answer for this kind of position](http://stackoverflow.com/a/17655598/287948). Most of the other answers are [copies of these](http://stackoverflow.com/q/5874652/287948) – Peter Krauss Oct 31 '14 at 03:13

4 Answers4

30

.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.

cHao
  • 78,897
  • 19
  • 136
  • 168
  • 7
    Case in point: `` If you use `attr("data-foo")`, you get back `"bar"`. If you use `prop`, you don't, you get `undefined`. You *could* use `data`, but that would make jQuery create a data object for your `span` and pre-populate it with all of the `data-*` attributes on the element, which is unnecessary if all you want is to get `data-foo` as a one-off. – T.J. Crowder Feb 25 '13 at 15:26
  • @cHao. Yes, but that is the point: jQuery programming is "DOM programming", and ALL HTML attributes was mapped to DOM objects... So, I think, for 99,9% of the jQuery applications, I not need to use attr. – Peter Krauss Feb 25 '13 at 15:26
  • 1
    @PeterKrauss: There's no purpose to be achieved by avoiding it. Don't bother trying to go out of your way to do so, it's just *unnecessary*. – T.J. Crowder Feb 25 '13 at 15:27
  • 2
    @PeterKrauss: *Not all*. Anything that's not supported by your browser isn't going to have an associated property. Anything that's not standard...same thing. Etc. – cHao Feb 25 '13 at 15:27
  • I think the OP means to ask if he can stop using `attr` in everyday tasks. And assuming he is not using non-standard HTML, I'd say he could "deprecate" it in his work based on your ansewr, instead of your conclusion? – Nanne Feb 25 '13 at 15:27
  • It's pretty common to use `.attr("data-somename")` it seems, but if you never need it, then you never need it. – Kevin B Feb 25 '13 at 15:28
  • @Crowder. Hum... yes, now I have a clue (!thanks), but not yet convencing me that it have more than 0,1% of relevance... – Peter Krauss Feb 25 '13 at 15:28
  • 1
    @Nanne: Eh. One *should* stop using it for tasks that don't specifically involve inspecting attributes. If there's a property that serves the purpose better, use `.prop()` instead. Otherwise, `.attr()` still definitely has its place. – cHao Feb 25 '13 at 15:29
  • But that was the question (I admit, not too well written), and you didn't add that to your answer? :confused: – Nanne Feb 25 '13 at 15:30
  • 5
    @PeterKrauss: You can also avoid using `for` loops if you want to. The point is, why would you want to? It serves no purpose. Use the right tool for the job. If you're grabbing an *attribute*, use `attr`. – T.J. Crowder Feb 25 '13 at 15:32
  • @Nanne: The question was, "Is there a good reason to use it?". Not "When should i stop using it?". :P – cHao Feb 25 '13 at 15:32
  • 4
    @Nanne: You're free to post such an answer if you like. I for one would downvote it as simply wrong, there *are* good reasons. If you're accessing an *attribute*, use `attr`. Not an edge case, a common case. – T.J. Crowder Feb 25 '13 at 15:36
  • @T.J.Crowder : I'm not posting that as an answer as I don't know the correct answer. (I would just copy this answer, and that would be useless). Maybe the difference in opinion is more "what is day to day use", And i'd rather see the question edited to reflect a more straightforward problem (why use attr()). – Nanne Feb 25 '13 at 15:40
  • 2
    @Nanne The primary example - non-standard/custom attributes - isn't a fringe case, it's something that most people writing JavaScript are going to (or should) be using often, so I'd say it definitely falls under the umbrella of "day to day use". – Anthony Grist Feb 25 '13 at 16:15
12

I took the liberty of preparing a fiddle for you:

http://jsfiddle.net/5REVP/

Especially this part:

<div id="example" style="padding:10px"></div>

console.log("style");
var styleAttr = $("#example").attr("style");
console.log(styleAttr); // You get "padding:10px"
var styleProp = $("#example").prop("style");
console.log(styleProp); // You get a CSSStyleDeclaration object

The "style" example shows clearly that an attribute is not the same as a property (check the console).

For readability, maintainability and backward (as well as forward) compatibility you should allways use the correct methods for a given task, otherwise there is a chance that a method may stop behaving as you though it would, the .attr() method is an example of that.

.attr() method is used to get attributes of elements, attributes are a SGML term that refers to the information contained inside the element tags, you can easily read that information by inspecting the elements.

  • If you get the "style" attribute of an element you will not get any information other than what is specifically written in that attribute.
  • If you get the "checked" attribute of a checkbox you will either get "checked" or "".

.prop() method is used to get DOM properties of elements.

  • If you get the "style" property you are not getting what the designer wrote in the style attribute, you are getting all the actual css properties of the element.
  • If you get the "checked" property of a checkbox you will get true or false.
cernunnos
  • 2,698
  • 1
  • 16
  • 17
  • @cernunnos, thanks by the good explanation and good clues... My point is that jQuery programming is "DOM programming", and all HTML attributes was mapped to DOM objects... So, I think, for 99,9% of the jQuery applications, I not need to use attr. As a developer I see that `style` *object* is better than a *string* for 99% of applications. – Peter Krauss Feb 25 '13 at 15:51
  • Actually most jQuery plugins manipulate attributes, not properties (one usually leads to the other, but it is not the same). When the objective is to manipulate the interface (html) it is always better to manipulate attributes, because other plugins/modules expect any relevant "non-default" behaviours to be "visible". I think you rarely need to change an elements properties, but accessing them is common (checked property of a checkbox). – cernunnos Feb 25 '13 at 16:00
  • 3
    +1 (`style` is a **great** example!) Nitpicking @FrédéricHamidi's nitpick: As of HTML5, [HTML is no longer an SGML application at all](http://www.w3.org/TR/html5/syntax.html#parsing): *"Some earlier versions of HTML...were based on SGML and used SGML parsing rules. However, few (if any) web browsers ever implemented true SGML parsing for HTML documents... The resulting confusion...has wasted decades of productivity. This version of HTML thus returns to a non-SGML basis."* Although nitpicking *myself*, that doesn't mean we're not talking about attributes in the SGML sense. :-) – T.J. Crowder Feb 25 '13 at 16:26
  • @T.J., excellent point. I like how they say *some earlier versions of HTML* instead of *pretty much all the earlier versions* :) – Frédéric Hamidi Feb 25 '13 at 18:19
  • @FrédéricHamidi: Quite. There basically wasn't an HTML1, so "HTML2 through HTML4" is a pretty large set. :-) – T.J. Crowder Feb 25 '13 at 18:34
  • great job on the answer, i was no aware of the difference and this example made it extremely clear! – Tony Oct 30 '14 at 15:11
2

.attr() only accesses HTML attributes, whereas .prop() will retrieve properties not on the HTML elements. See the documentation:

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.

http://api.jquery.com/prop/

Joshua
  • 3,605
  • 1
  • 24
  • 32
0

My homework... After read @cHao and @cernunnos good explanations, and after some months using it... I thing we need another concept to decide, as programmer, when use or not prop and attr:

  • HTML source-code and its representation: the browser loads HTML page in the browser's memory space. Well, what stay at memory's browser is the DOM representation, but DOM preserves some original things, as attributes and cssText property, that are "sometimes persisted representations".
    PS: attributes that are not defined in the "standard DOM", have not a mapping to DOM properties. When one (not read-only) attribute changes, if there are corresponding (mapped) property, it can be changed automaticlally.

  • DOM state: dynamical pages need changes directly at the DOM, that is what final users see. So, if there are some "click and change" actions at the page, each time the DOM goes to a new page representation, so, each time DOM have a new state.
    When one DOM-property changes, all other DOM properties (if need) changes consistently.

With these concepts in mind, we can draw a "rule of thumb (for attr vs prop uses)":

  1. Use prop, you have 90% of chances that it works... 99% if you using jQuery for change DOM states (and standard DOM hypothesis).
  2. If you need to change or access to data-* attributes, use .data() method.
  3. Otherwise (non-DOM, non-data, or non-standard things) check if a case of use .attr(), and reserve some time to study it (see answers above).
Peter Krauss
  • 11,340
  • 17
  • 129
  • 247
  • 2
    a bit offtopic, but why if this answer is the ACCEPTED one, it is not on top of the others? Usually the accepted goes first, even if other answers have more votes... Here it is LAST! – DiegoDD Jul 03 '14 at 16:35
  • 1
    @DiegoDD, sorry some months later... Because NO ONE reads the question, **it is a "different question" than cited similars**... The answers here, in that time, are **all only COPY/PASTED** answers **from the similar ones**. – Peter Krauss Oct 30 '14 at 22:49