Get all images from a div ID and add links
I am having some difficulties building a javascript that gets all the images from a div ID, and add a link to the big image on each of the thumbnails. Here is my code.
<html>
<head>
<script>
function addGallery(){
var getDivId = document.getElementById("imgContainer");
var images = getDivId.getElementsByTagName("img").innerHTML;
for(var i=0; i<images.length; i++) {
getDivId.innerHtml = "<a id='g2Image' href='big/" + images[i].src + "'>" + images[i].src + "</a>";
}
}
</script>
</head>
<body onload='addGallery()'>
<div id="imgContainer">
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" wid开发者_StackOverflow社区th="125" height="100" />
</div>
</body>
</html>
Thank you in advance! Regards.
You are assigning innerHTML in each loop without concatenating the existing HTML.
Change:
getDivId.innerHTML = "<a id='g2Image' href='big/" + images[i].src + "'>" + images[i].src + "</a>";
to
getDivId.innerHTML += "<a id='g2Image' href='big/" + images[i].src + "'>" + images[i].src + "</a>";
Um... you're actually attempting to grab an object property from an array, which doesn't exist:
var images = getDivId.getElementsByTagName("img").innerHTML;
Should be changed to:
var images = getDivId.getElementsByTagName("img");
Edit 2
Note than in IE, the image.src
value will be the full path of the image so you can't just prepend 'big/' to them.
Edit
Oops, didn't see that you were adding A elements. Presumably you want the images to be inside the link. Instead of innerHTML, you can use DOM methods to creat the links:
function addGallery(){
var getDivId = document.getElementById("imgContainer");
var path = '/images/galleries/';
var images = toArray(getDivId.getElementsByTagName("img"));
var oA = document.createElement('a');
var a, image, parent;
for(var i=0, iLen=images.length; i<iLen; i++) {
image = images[i];
a = oA.cloneNode(false);
a.href = image.src.replace(path, '/big' + path);
image.parentNode.appendChild(a);
a.appendChild(image);
}
}
function toArray(a) {
var result = [];
var i = a.length;
while (i--) {
result[i] = a[i];
}
return result;
}
There is also a document.images collection that is all the images in the document, but likely you only want those in the div.
精彩评论