Adding elements to a div using the appendchild attribute
I have a div like:
<div id="div1" width="100px" height="100px"> </div> Now in this div I want to place 20 elements, but dynamically it can grow up to 50 elements (images).
I use the following code to add these elements to a div,
var i = document.createElement("img"); var d= document.getElementById("div1"); d.appendchild(i); Now the problem is that as the number of elements increases, the elements exit the div, and if I use the maximum width and maximum height in the images, the result does not change:
i.setAttribute('max-width', '100%'); i.setAttribute('max-height', '100%'); Is there anything that I am missing?
Edit: Images should shrink at a fixed div size
If the width is fixed and the height is dynamic. The image will be reduced and they will be folded. Check out my fiddle here
img { width:100%; display:inline-block; } <div style="width:100px;border: 1px solid black;"> <img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" /> <img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" /> <img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" /> </div> Can't think of a good way to do this with interest,
var imags = document.getElementsByTagName('img'); var count = imags.length; for (var index= 0,l= count;index<l;index++){ imags[index].setAttribute('height', (100/count)+'%');; } its not really, but it should work.
I put together something along with all the answers that fit your needs (if I understand you correctly)
https://jsfiddle.net/b30d88g6/3/
div has a fixed width / height and images will not exit the div
function add_img() { var i = document.createElement("img"); i.src= "https://jsfiddle.net/img/logo.png"; var d= document.getElementById("div1"); d.appendChild(i); var imags = document.getElementsByTagName('img'); var count = imags.length; for (var index=0, l=count;index<l;index++){ imags[index].setAttribute('height', (100/count)+'%');; } }