Skip to main content

Bug Tracker

Side navigation

#10671 closed bug (duplicate)

Opened November 04, 2011 03:02PM UTC

Closed November 04, 2011 04:43PM UTC

Last modified November 04, 2011 06:59PM UTC

attr('attribute', undefined) doesn't return jQuery

Reported by: pilif Owned by:
Priority: low Milestone: None
Component: attributes Version: 1.7
Keywords: Cc:
Blocked by: Blocking:
Description

Calling .attr() or anything else deferring to access() with a second argument of undefined returns undefined instead of jQuery.

 typeof($('div').attr('id', undefined)) === 'undefined';

See here: http://jsfiddle.net/tkjXt/

I know that you probably shouldn't set an attribute (or anything else) to undefined, but this is handy when copying attributes from another element:

  $('<div>')
    .attr('id', otherdiv.attr('id')) // if otherdiv doesn't have an id, we blow up here.
    .attr('class', otherdiv.attr('class'));

This worked correctly before jQuery 1.6 but broke when attr('doesnotexist') began returning undefined.

I would have sent a patch, but attr() then immediately defers to access() which has no way to find out whether attr() was called with one or two parameters, so fixing this would be a huge refactoring effort I definitely don't feel comfortable with.

Attachments (0)
Change History (3)

Changed November 04, 2011 04:43PM UTC by timmywil comment:1

component: unfiledattributes
priority: undecidedlow
resolution: → duplicate
status: newclosed

This is intentional for all jQuery setters.

Changed November 04, 2011 04:43PM UTC by timmywil comment:2

Duplicate of #9427.

Changed November 04, 2011 06:59PM UTC by dmethvin comment:3

_comment0: To your specific case, I think this would work: \ {{{ \ $('<div>') \ .prop('id', otherdiv.prop('id')) \ .prop('class', otherdiv.prop('class')); \ }}} \ Those two corresponding properties are always defined (but can be empty strings, which is fine). You could also `.clone()` the original div and modify it, which could be faster and shorter.1320433226570512

To your specific case, I think this would work:

  $('<div>')
    .prop('id', otherdiv.prop('id')) 
    .prop('className', otherdiv.prop('className'));

Those two corresponding properties are always defined (but can be empty strings, which is fine). You could also .clone() the original div and modify it, which could be faster and shorter.