On 12/4/06, troels knak-nielsen <[EMAIL PROTECTED]> wrote:
>
> I just encountered some really weird behaviour with MochiKit.Iter - Is
> this expected behaviour, or a bug?
>
> <html>
> <head>
> <title>forEach vs getElementsByTagName</title>
> <script type="text/javascript" src="res/mochikit.js"></script>
> </head>
> <body>
>
> <div id="container">
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
>         <span>&nbsp;</span>
> </div>
>
> <script type="text/javascript">
>         var container = $("container");
>         var it = container.getElementsByTagName("span");
>         var len1 = it.length;
>         var len2 = 0;
>         forEach(container.getElementsByTagName("span"), function(span) {
>                 span.parentNode.removeChild(span);
>                 len2++;
>         });
>         alert("length 1 = " + len1 + "\n" + "length 2 = " + len2 + "\n");
> </script>
> </body>
> </html>
>
> Expected output is 8 in both cases, but only the first method does
> that. Using forEach, I get only 4. This clearly has something to do
> with the fact that I'm manipulating the DOM inside the callback, but I
> would have expected an iterator to be immutable ?!?

That's expected behavior.. the same thing would happen with::

    for (var i = 0; i < nodes.length; i++) { ...; }

The result of dom.getElementsByTagName is not an Array, it's a list of
nodes that changes when the DOM does, which not only makes it slow but
error prone as you can see.

It would've worked as you expect if you were using
getElementsByTagAndClassName("span", null, container), because it
returns an Array.

-bob

--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the Google Groups 
"MochiKit" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/mochikit?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to