Bug Tracker

Ticket #6205 (closed bug: invalid)

Opened 5 years ago

Last modified 5 years ago

.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:
Blocking: Blocked by:

Description

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() {
  d.add(this);
});
alert('divs, using add() in a loop: '+d.length);

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

Change History

comment:1 Changed 5 years ago by john

  • Status changed from new to closed
  • Resolution set to invalid

.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 5 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.