Bug Tracker

Opened 13 years ago

Closed 13 years ago

Last modified 13 years ago

#6205 closed bug (invalid)

.add() not working on cached jQuery object

Reported by: markahon Owned by:
Priority: Milestone: 1.4.3
Component: traversing Version: 1.4.2
Keywords: Cc:
Blocked by: Blocking:


Can't use $.fn.add to add more elements into a cached jQuery object containing DOM elements.

If this works as intended, then at least the documentation on http://api.jquery.com/add/ is not clear about this, and then why shouldn't it be allowed?

I stumbled into this when I wanted to use .add() inside a loop to add an element into a collection, if certain criteria is fulfilled. The jQuery object containing the elements that fulfilled the criteria would be processed later.

Test code:

var d = $('div');
alert('divs: '+d.length);

// using add(), this failed
d = $();
$.each($('div'), function() {
alert('divs, using add() in a loop: '+d.length);

// workaround
d = [];
$.each($('div'), function() {
alert('divs, using array workaround: '+$(d).length);

Change History (2)

comment:1 Changed 13 years ago by john

Resolution: invalid
Status: newclosed

.add() doesn't modify the existing object, it returns a new object with the values in it - it's more like using .concat() then .push.

comment:2 Changed 13 years ago by markahon

Ah, thank you for the quick answer. This was revealing, before now it had somehow felt natural to assume that the existing object is modified when the traversing functions are used.

Note: See TracTickets for help on using tickets.