user2197114
user2197114

Reputation:

AppendChild Javascript

I am trying to append images to a bootstrap column but having no luck, does anyone know what is wrong with my code.

for (i = 0; i <= 11; i++) {
     var img = new Image();
     img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
     var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
     document.body.appendChild(row);
}

Any help is appreciated. Thanks

Upvotes: 0

Views: 152

Answers (2)

jfriend00
jfriend00

Reputation: 707158

Sorry, but your code doesn't really make any sense. There are lots of things wrong with it:

Here's what you started with:

for (i = 0; i <= 11; i++) {
     var img = new Image();
     img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
     var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
     document.body.appendChild(row);
}

Issues:

  1. You create an <img> DOM object, but don't do anything with it.
  2. You need to pass a DOM object to appendChild() NOT pass a string.
  3. You can't construct a string of HTML by adding img[0] into the string. It simply doesn't work that way at all. You either work entirely in HTML strings or you work in constructed HTML objects or you create an HTML object and then set .innerHTML to a string of HTML. You can't just mix the two the way you are.

I'll take a guess at what you want to do:

for (i = 0; i <= 11; i++) {
     var src = "http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i];
     var row = document.createElement("div");
     row.className = 'row';
     row.innerHTML = "<div class='col-md-2'><img src='" + src + "'></div>";
     document.body.appendChild(row);
}

This code take the following steps:

  1. Calculate the image src URL.
  2. Create your container div DOM object.
  3. Set the desired className on the container object.
  4. Set the .innerHTML property of the container to the HTML string for the HTML that you want in the container (this will automatically create that set of DOM objects in the container).
  5. Append the container to your document.

Upvotes: 3

km6zla
km6zla

Reputation: 4877

Here is an all-javascript solution

var camera = ['http://placehold.it/200x200']

for (i = 0; i <= 0; i++) {
    var img = new Image();
    img.src = camera[i];
    var row = document.createElement('div');
    row.className = 'row';
    var imgContainer = document.createElement('div');
    imgContainer.className = 'col-md-2';
    imgContainer.appendChild(img);
    row.appendChild(imgContainer);
    document.body.appendChild(row);
}

and a jsfiddle demo http://jsfiddle.net/576Tm/1

Upvotes: 0

Related Questions