Becky
Becky

Reputation: 5585

Create divs and add images on the fly

I'm creating 4 divs and adding 4 images in to each div.

var divid = ["aa","bb","cc","dd"], 
    imgid = ["a.png","b.png","c.png","d.png"];
for(var i = 0; i < divid.length;i++ ){
   document.write('<div id="'+divid[i]+'" class="divCl"><input type="image" src="'+imgid[i]+'" class="imgCl"/></div>');
}

css:-

.divCl{
   /*display: none;*/
}
.imgCl{
   width: 100px;
   height: 100px;
}

Why isn't the css applying? also is it ok to use this method to create divs and add images?

Upvotes: 0

Views: 75

Answers (3)

Joshua Whitley
Joshua Whitley

Reputation: 1186

Well, document.write will overwrite the entire contents of the DOM once the document is loaded so you should not use this. You should instead use document.getElementById to select the parent element where you want to insert the images and then set the .innerHTML of that element to the new images. Here is an example:

HTML

<div id="imgParent"></div>

JS

var divid = ["aa","bb","cc","dd"], 
    imgid = ["a.png","b.png","c.png","d.png"];
var imgs = '';

for(var i = 0; i < divid.length;i++ ){
   imgs += '<div id="'+divid[i]+'" class="divCl"><input type="image" src="'+imgid[i]+'" class="imgCl"/></div>';
}

var parent = document.getElementById('imgParent');
parent.innerHTML = imgs;

Output HTML

<div id="imgParent">
    <div id="aa">
        <input type="image" src="a.png" class="imgCl" />
    </div>
    <div id="bb>
        <input type="image" src="b.png" class="imgCl" />
    </div>
    ...
</div>

Upvotes: 1

user2085955
user2085955

Reputation: 104

Going the document.write route will cause your CSS (and everything else) to be overwritten. A better way would be to create a container div and place the new div's in there

var divid = ["aa","bb","cc","dd"], 
imgid = ["a.png","b.png","c.png","d.png"];

for(var i = 0; i < divid.length;i++ ){
    document.getElementById('containerDiv').innerHTML += '<div id="'+divid[i]+'" class="divCl"><input type="image" src="'+imgid[i]+'" class="imgCl"/></div>'
}

You could also just add it directly to the body by doing

document.getElementsByTagName('body')[0].innerHTML

Upvotes: 0

andybeli
andybeli

Reputation: 856

There is a syntax error. Your arrays elements are not strings. The elements are variables not defined. I used jQuery to append each div to the body.

var divid = ['aa','bb','cc','dd'], 
    imgid = ['a','b','c','d'];

for(var i = 0; i < divid.length; i++ ) {
   var str = $('<div id="'+ divid[i] +'" class="divCl"><input type="image" src="'+ imgid[i] +'" class="imgCl"/></div>');
   $('body').append(str);
}

https://jsfiddle.net/hjepjnk3/

Upvotes: 0

Related Questions