質問

I'm very much a beginner at Javascript, so keep that in mind for any small inefficiencies in my code.

I'm attempting to set the IDs of a group of divs "galleryboxes" (that are inside a another div, "galleryimages") to be increasing increments, ie. picture1, picture2, etc.

Inside each div (from 'galleryboxes') is one picture each; in the second line of my for loop I'm attempting to do the same as to the div above and give them an id. I then want to use this picture to make a thumbnail from it (posted to the div 'gallery').

var galleryimages = document.getElementById("galleryimages");
var galleryboxes = galleryimages.getElementsByTagName("div");

var k = 1;
var thumbimage = document.createElement("img");

for (var i = 0; i < galleryboxes.length; i++) {
    galleryboxes[i].id = "item" + k;
    galleryboxes[i].getElementsByTagName("img").id = "picture" + k;
    thumbimage.src = document.getElementById("picture" + k).src;
    document.getElementById("gallery").appendChild(thumbimage);
    //thumbimage.className = "thumbnail";
    k++;
}

Unforunately, when I 'appendChild', it just says it can't read the .src property of null. I've tried re-arranging a few things, but I can't get just the image to make a thumbnail from it. I'm fairly sure I've assigned the ID to the right item...

Along with that, my commented out code is trying to assign the new thumbnail a class, which for the few times I've gotten close to getting this to work didn't seem to work itself. Is there any clear thing wrong there?

役に立ちましたか?

解決

I noticed two problems:

1) you create only 1 thumbimage, but iterate through an array of galleryboxes

2) getElementsByTagName returns a list of elements (NodeList), and you set the .id of the NodeList. If you are sure there is exactly 1 img, use getElementsByTagName()[0].

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top