Tuesday, November 4, 2008

To access elements and childs from Javascript to your XML

You'll probably already know how to access an element from Javascript, By it's name. But what if you added a dynamic elements from Javascript and then wanted to access them all again? One by one, by the names? Sounds harsh. The solution is to loop through the all. This can be done in several ways but I'm going to show you one.
If you have a combobox in your gadget and add dynamic items and labels to it by the method appendString. It's impossible then to access them by name as they don't have one yet. But imagine this, we write a combobox in the XML file like this:

<combobox name="cb"
height="100" width="125"
itemWidth="100%"
itemHeight="16"
maxDroplistItems="5"
type="droplist">
</combobox>

Then we fill the combobox with items containing labels from javascript coding:

for(var i = 0; i < array.length; i++)
{
cb.appendString(array[i].name);
}

An array with names will be filling the combobox here, the result in xml would look like this:

<item>
<label>Name 1</label>
</item>
<item>
<label>Name 2</label>
</item>...

Now, how do we do if we want to put a property to the labels, lets say a different size? By this, from javascript again:

for(var i = 0; i < cb.children.count; i++)
{
element = cb.children.item(i).children.item(0);
element.size = 7;
}

By the children property we can access all elements to the combobox and then access that particular item. You see you have to first get the children of the combobox and that are the <item> elements, from there we have to access their children and they are the <label> elements. There are other ways to access elements in the XML file from javascript, this was one way. Instead of writing item(i) or item(0) you can access a child by it's name by writing the name instead item("childName"). Also you can use the enumerator object.

No comments: