3

I have code (using jQuery) like the following:

var $parent = $('#parentContainer');
$.each([[],[],[],...[]], function(index, innerArray) {
    $.each(innerArray, function(innerIndex, innerValue) {
        $parent.append($('<div />', { ... }));
    });
});

I know this is massively inefficient. I originally tried this with $.map instead of $.each. I would return the DIVs from the inner $.map and each of those arrays would be returned from the outer $.map. Then I would try something like $parent.append(arrayOfArrays). I would then get an uncaught exception some time later. The code with $.each works but I know there is another way using arrays and appending them all at once. Was I even close with the $.map implementation? Am I missing another way? thanks By the way, i am a total newb at this so I realize I may be doing this totally wrong.

2
  • I'm a bit puzzled. May you explain better what you want to achieve? Commented May 8, 2011 at 6:11
  • @Eineki: Maybe I made my example more confusing than it needs to be. My problem would be the same with only a single loop. I need to append a number of divs to a parent container. The above is my quick & dirty method because I know it works. I would like to use $.map because that returns an array of the divs. But, when I tried using $.map I got an exception. Commented May 8, 2011 at 6:59

2 Answers 2

4

I'm not entirely sure what you're trying to achieve here, but on general principles, injecting directly into the DOM tends to be slow. Injecting into the DOM in a loop is therefore going to be very slow.

A better approach is to build up your collection of elements to insert in the loop, and then append() the entire collection when the loop is finished. This replaced multiple DOM updates with a single one, taking the expensive DOM updating out of the loop.

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

1 Comment

That is exactly what I was trying to do with my original $.map implementation but it caused problems. I didn't have the time to investigate so I just used the quick and dirty method I have shown above. According to the API I should be able to do $parent.append([div, div, div, div,...]); Maybe it can't handle and array of arrays which is what I would have been sending it.
3

construct your html and do a appened after the loop

like this eample

noteffective

var arr = reallyLongArray;
$.each(arr, function(count, item) {
    var newTr = '<tr><td name="pieTD">' + item + '</td></tr>';
    $('table').append(newTr);
});

effective

var arr = reallyLongArray;
var textToInsert = '';
$.each(arr, function(count, item) {
    textToInsert  += '<tr><td name="pieTD">' + item + '</td></tr>';
});
$('table').append(textToInsert);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.