Javascript getElementsByTagName("div") what am I labeling?

MattTreichel picture MattTreichel · Dec 22, 2012 · Viewed 7.1k times · Source

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.

I've seen questions similar to this and tried to get my head around them, but it's difficult. Right now my questions are, what do I get from the second line here? What is 'galleryboxes'? Am I able to cycle through it like an array and label ids like I'm attempting to?

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

var k = 1;

for (var i = 0; i < galleryboxes.length; i++) {
galleryboxes[i].setAttribute=("id", "picture" + k);
k++;
}

The code seems to work, but I don't think I'm actually labeling the divs I want to be labeling; I check what the contents are of "picture1" and it comes up as null (It should be full of a picture and some text).

Answer

0x499602D2 picture 0x499602D2 · Dec 22, 2012

What do I get from the second line here?

The line in question is this:

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

What this does is provide a live nodeList complete with all the elements with the tag name <div> that are child to the element which the variable galleryimages represents. Note that this is not an actual array, and there are distinguishing characteristics between an array and a nodeList. Most notably, a nodeList does not inherit from the Array constructor, and thus does not contain essential methods like push, pop, and sort common to all arrays.

Am I able to cycle through it like an array and label ids like I'm attempting to?

Yes. This is made easy for us because fortunately nodeLists have a length property. You've already showed how you can loop through them, but the line on which you set the attribute is ill-formed:

galleryboxes[i].setAttribute=("id", "picture" + k);

The equal sign should not be there. This invokes a syntax error. If you take the equal out, the code works fine.