Farzher
Farzher

Reputation: 14563

How to merge array of LARGE jQuery objects into one?

I'm trying to use jQuery's add function... but when merging objects of 3000+ dom elements, it freezes up. Is there any faster way I can achieve this?

var a = [];
a[0] = $('small');
a[1] = $('.no');
a[2] = $('.yes');
//a is array of jQuery objects

//make b an empty jQuery object. loop through a, adding each to b
var b = $();
for(var i in a) {
    b = b.add(a[i]);
}
//browser freezes for a bit
console.log(b);

Edit: Don't question why I have so many DOM elements, I'm stress testing a jQuery plugin I'm writing :D

Upvotes: 0

Views: 537

Answers (2)

Tats_innit
Tats_innit

Reputation: 34107

This might help: API: http://api.jquery.com/jQuery.merge/

$.merge( [0,1,2], [2,3,4] )

Please lemme know if I am missing anything, rest this api should help you to merge. :)

The $.merge() operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended. The $.merge() function is destructive. It alters the first parameter to add the items from the second.

var a = [];
a[0] = $('small');
a[1] = $('.no');
a[2] = $('.yes');

// now to merge 2 arrays

$.merge( a, b) // a & b are arrays.

Upvotes: 1

Andy Ray
Andy Ray

Reputation: 32066

Despite my comment, you could just do

$('small, .no, .yes')

Upvotes: 5

Related Questions