Ticket #8770 (closed enhancement: wontfix)
Document `attr` behavior when new value function returns undefined
| Reported by: | tj@… | Owned by: | |
|---|---|---|---|
| Priority: | low | Milestone: | 1.next |
| Component: | attributes | Version: | 1.5.2 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
(Neither a bug nor a feature...let's go with enhancement.)
When you call attr with a function, but then don't return a value out of the function (or return undefined), the attribute isn't changed. This is exactly the behavior I want for modifying the attribute only when it meets a certain condition, e.g.:
$("some_selector").attr("data-foo", function(index, value) { if (meetsCriteria(value)) { return updatedValue(value); } });
Example: http://jsfiddle.net/cGtY5/
If it's intentional/desirable, could we document it ( here)?
Change History
comment:1 Changed 2 years ago by timmywil
- Keywords needsdocs added
- Priority changed from undecided to low
- Status changed from new to closed
- Component changed from unfiled to attributes
- Resolution set to wontfix
comment:2 Changed 2 years ago by addyosmani
- Keywords needsdocs removed
Updated: http://api.jquery.com/attr/
comment:3 Changed 2 years ago by tj@…
Great to see the docs updated so quickly (some projects take months to make similar changes), but the wording seems awfully confusing. Perhaps simply:
Note: If the setter function doesn't return a value or returns undefined, the current value of the attribute is not changed. This can be useful for only changing the attribute when certain criteria are met in the setter function.
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

That seems like the right behavior to me. I think we could add something saying if nothing is returned in the setter function, the current value is returned since it acts like a getter when the value is undefined, or simply that there will not be any changes made if the setter function does not return something.