Search code examples
jqueryjquery-selectorsjquery-append

Append collection of elements to another collection in jQuery


I'd like to append outside loop. I've got 2 collections. One of the elements that I want to append, and one of the elements that I want to append to. Namely, I have one collection of 3 divs and one collection of 3 paragraphs.

I want to append so that paragraph 1 will be appended to div 1, pragraph 2 to div 2 and paragraph 3 to div 3.

Is that possible without using a loop?

Right now I am doing it this way:

var divs = $('<div>'), paragraphs = $(), arr = [['class1','text1'],['class2','text2'],['class3','text3']];
for (i = 0; i < 3;i++)
{
    paragraphs = $('<p class="' + arr[i][0] + '">' + arr[i][1] + '</p>').appendTo(divs.eq(i));
}

Solution

  • EDITED, due to changes in original example, improved answer yes internally it will use a loop anyway, but i think what you are asking for is

    divs = $('div'), paragraphs = $(), arr = [['class1','text1'],['class2','text2'],['class3','text3']];
    divs.append(function(i, h){
        paragraphs = $('<p class="' + arr[i][0] + '">' + arr[i][1] + '</p>').appendTo(divs.eq(i));
        return paragraphs;
    });
    

    Hope this helps

    Note: in the question you wrote

    divs = $('<div>');
    

    and it should be

    divs = $('div');