sp1d3rx@gmail.com wrote:
Quote:
-----------code:------------- (whitesmiths indentation)
>
function PopulateUlList()
{
alert("started populating...");
var ulz = inter.getElementsByTagName("ul");
alert(ulz.length);
for(x in ulz)
{
alert(ulz[x].id);
}
}
-------------html-------------
<div id='inter'>
<ul id="cute"></ul>
<ul id="ugly"></ul>
</div>
--------------------------
When this code is run in Firefox 2.0, it alerts the following...
>
"started populating..."
"2"
"cute"
"ugly"
"undefined"
"undefined"
>
Why does it say 'undefined' ? Also, changing the loop from a "for in"
to a "for" loop (for(x = 0; x < ulz.length; x++)), I no longer get the
problem. Why can't I use "for in" ?
You can, but as web.dev said, it will return *all* the enumerable
properties of an object. document.getElementsByTagName() returns a
NodeList object:
<URL:
http://www.w3.org/TR/DOM-Level-2-Cor...tml#ID-A6C9094 >
For an HTML document, this object also implements the HTMLCollection
interface:
<URL:
http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-75708506 >
If you change your script slightly to show the property name also,
you'll discover what those 'undefined' properties are:
alert(x + ': ' + ulz[x].id);
In Firefox there's length, item and namedItem. IE exposes length, the
other two properties are there but aren't enumerable. Since the W3C
DOM spec doesn't say what should or shouldn't be enumerable, both
behaviours are OK from that perspective.
A for loop works because the items in a NodeList have numeric property
names, like an array. The for loop iterates over just those, skipping
the ones with non-numeric names. Note that even though the names are
numeric (0, 1, 2, etc.) they are strings, not numbers.
The HTMLCollection interface also allows you to use the ID to reference
DOM elements in the collection, e.g.:
alert( typeof ulz['cute'] );
--
Rob