Guy Aston
Guy Aston

Reputation: 169

Create an element and append it to multiple elements using jQuery

im trying to create 2 divs that will contain a few images, the same images (2 logos strips that looks the same) - all dynamically.

this is my code:

//those are my vars
var logos = ['logo1','logo2','logo3'];
var $stripLogo; //will use later to create the images
var $stripContainerA = $('<div>', {class: 'stripContainer', id: 'stripA'}); //Container 1
var $stripContainerB = $('<div>', {class: 'stripContainer', id: 'stripB'}); //Container 2

//and this is how i append it
$('#logosStrip').append($stripContainerA); //Insert container 1 into an existing element
$('#logosStrip').append($stripContainerB); //Insert container 2 into an existing element

for(var i = 0; i < logos.length; i++) {
    $stripLogo = $('<img/>', {class: 'stripLogo', src: 'img/logos/' + logos[i] }); //Create an image

    $stripContainerA.append($stripLogo); //append image to container 1
    $stripContainerB.append($stripLogo); //append image to container 2
}

the thing is, it seems like it can only append the img to 1 container, and not both. what is wrong with the code?

i hope its clear enought

Upvotes: 2

Views: 842

Answers (1)

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2596

The error is really simple once you spot it. You're creating an jQuery Object Image $("<img/>").

You iterate three times in your for loop

var logos = ['logo1','logo2','logo3']; // Three keys

for(var i=0; i < logos.length; i++) {  // Three times
    var $img= $('<img/>',{src:"bla"}); // Three times

}

means only three Object images will be created.
Now let's explore one loop iteration:

var $img= $('<img/>',{src:"bla"}); // ONE! in-memory image is created.
$A.append($img);                   // append it to A
$B.append($img);                   // no, wait....now append it to B !!!

it first appeared in A element but than quickly goes to B cause Objects work by reference.

Try appending the html directly or clone de DOM element.

for(var i = 0; i < logos.length; i++) {
    $stripContainerA.append('<img class="stripLogo" src="img/logos/' + logos[i] + ' />");
    $stripContainerB.append('<img class="stripLogo" src="img/logos/' + logos[i] + ' />");   
}

// OR
for(var i = 0; i < logos.length; i++) {
    $stripLogo = $('<img/>', {class: 'stripLogo', src: 'img/logos/' + logos[i] }); //Create an image

    $stripContainerA.append($stripLogo.clone()); //append image to container 1
    $stripContainerB.append($stripLogo.clone()); //append image to container 2
}

Upvotes: 4

Related Questions