Tip: Enumerating child elements of an object

Friday, January 04, 2008 at 3:46 PM



UPDATE (June 19): The post has been modified to demonstrate element.children.item() instead of element.children() which is not supported on Mac and Linux.

It's often useful to iterate through children of a div or view for resizing or debugging. You can do this in a few ways. Let's say I have a gadget with the following XML specification:
<view width="200" height="200">
<div name="parent_div">
<img name="child_1" />
<label name="child_2" />
<div name="child_3" />
</div>
</view>
Whoops! I've forgotten to set the opacity of the children. We can do that in JavaScript.

Option 1: Enumerating using the child's name

for (var i = 1; i < 4; ++i) {
var element = parent_div.children.item("child_" + i);
element.opacity = 150;
}

Option 2: Using the count

for (var i = 0; i < parent_div.children.count; ++i) {
var element = parent_div.children.item(i);
element.opacity = 150;
}

Option 3: Using the Enumerator object

UPDATE (June 19): This technique only works on Windows.
for (var e = new Enumerator(parent_div.children); !e.atEnd(); e.moveNext()) {
var element = e.item();
element.opacity = 150;
}
Have a tip you'd like to share? Send it to gd-developer AT google DOT com.

3 comments:

art said...

I think there might be a typo here:

for (var i = 0; i < parent_div.children.count(); ++i) { var element = parent_div.children(i); element.opacity = 150;}

I think you want the property of count, like so:
parent_div.children.count
I kept getting method not defined errors.

So I think you want:
for (var i = 0; i < parent_div.children.count; ++i) { var element = parent_div.children(i); element.opacity = 150;}

thanks for the tips!
Art Shectman
Gadget Developer
http://www.elephantventures.com

Kathy Walrath [GD Team] said...

Art, you're absolutely right. Thanks for pointing out the problem! I've fixed the post.

phnixwxz said...

1. children(i) is not defined in the API. You should use children.item(i) instead to ensure gadget portability.
2. Enumerator is Microsoft JScript thing. Thought it is simulated on mac and Linux version of gadgets, the simulations are not complete. So you'd better not to use them.