Ticket #8699 (closed bug: fixed)
.attr() returns -1 on missing attribute instead of undefined
| Reported by: | anonymous | Owned by: | timmywil |
|---|---|---|---|
| Priority: | blocker | Milestone: | 1.6 |
| Component: | attributes | Version: | 1.5.1 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
When element(s) are missing the attribute, attr works as follows.
$('elem').attr('noattr') == -1
This is a change from 1.4 where .attr() returned "undefined" or some other "falsy" response. Since -1 isn't considered falsy by javascript the following code is now broken.
if ($('elem').attr('noattr')) { doStuff();}
else { doOtherStuff();}
If the intended attribute check is now -1 please update documentation so we can update code, or fix the regression that makes this fail a boolean check.
Change History
comment:2 follow-up: ↓ 3 Changed 2 years ago by anonymous
i think i got this one right.
I'm loading jquery in the head, but the code that runs is in a document ready function.
comment:3 in reply to: ↑ 2 Changed 2 years ago by anonymous
Replying to anonymous:
i think i got this one right.
Meaning i've never used JSfiddle before, so i'm not 100% sure i replicated the test here correctly.
comment:4 follow-up: ↓ 5 Changed 2 years ago by timmywil
Nice catch! You are correct and I never noticed that before.
Nevertheless, this has been fixed in the upcoming attrHooks updates for jQuery 1.6. http://jsfiddle.net/timmywil/uyLQL/9/
comment:5 in reply to: ↑ 4 Changed 2 years ago by anonymous
Replying to timmywil:
Nice catch! You are correct and I never noticed that before.
Nevertheless, this has been fixed in the upcoming attrHooks updates for jQuery 1.6. http://jsfiddle.net/timmywil/uyLQL/9/
As long as I know it's fixed later on, I suppose I can wait. :P Back to vanilla dom for now i guess.
comment:6 Changed 2 years ago by timmywil
If it helps, the way we retrieve maxLength in 1.6 is by using node.getAttribute('maxLength') rather than the property node.maxLength. Perhaps we could put a quick update for maxlength in 1.5.2, but since attr is getting a rewrite, my guess is that it's not the highest priority.
An example with raw js: http://jsfiddle.net/timmywil/uyLQL/10/
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

Please provide a test case on http://jsfiddle.net. Non-existing attributes should return undefined. http://jsfiddle.net/timmywil/2Ymea/