Modify ↓
Ticket #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: | ||
| 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
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.
Note: See
TracTickets for help on using
tickets.

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