0

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

2
  • 1
    why are you merging 3,000 dom elements? can you do something that just affects the parent of all of them? or better yet, store your data independent of the dom so you don't have to touch it at all? Commented Aug 7, 2012 at 1:33
  • Why do you need to have 3000+ DOM elements selected in one jQuery object? Commented Aug 7, 2012 at 1:34

2 Answers 2

5

Despite my comment, you could just do

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

Sign up to request clarification or add additional context in comments.

1 Comment

Haha, yes. This is good advice and I'll vote it up so others can see it. But for what I'm doing I need to do it in different objects.
1

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.

3 Comments

Changing b = b.add(a[i]); to b = $.merge(b, a[i]); made it instant. Thanks!
@StephenSarcsamKamenar MAGIC!! Saweet man! :) Glad it helped you!
Just so others know. The reason this is so much faster is because it doesn't try to remove duplicate elements, while add does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.