Bug Tracker

Ticket #8699 (closed bug: fixed)

Opened 4 years ago

Last modified 3 years ago

.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:1 Changed 4 years ago by timmywil

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

comment:2 follow-up: ↓ 3 Changed 4 years ago by anonymous

i think i got this one right.

 http://jsfiddle.net/uyLQL/6/

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 4 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 4 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 4 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 4 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/

comment:7 Changed 4 years ago by rwaldron

  • Priority changed from undecided to blocker
  • Status changed from new to open
  • Component changed from unfiled to attributes
  • Milestone changed from 1.next to 1.6

comment:8 Changed 4 years ago by ajpiano

  • Owner set to timmywil
  • Status changed from open to assigned

comment:9 Changed 3 years ago by timmywil

  • Status changed from assigned to closed
  • Resolution set to fixed
Note: See TracTickets for help on using tickets.