javascript - Create divs and add images on the fly -


i'm creating 4 divs , adding 4 images in each div.

var divid = ["aa","bb","cc","dd"],      imgid = ["a.png","b.png","c.png","d.png"]; for(var = 0; < 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 css applying? ok use method create divs , add images?

well, document.write overwrite entire contents of dom once document loaded should not use this. should instead use document.getelementbyid select parent element want insert images , set .innerhtml of element new images. here 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 = 0; < 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> 

Popular posts from this blog