forEach vs getElementsByTagName

7 views
Skip to first unread message

troels knak-nielsen

unread,
Dec 4, 2006, 10:56:11 AM12/4/06
to MochiKit
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 ?!?

--
troels

Bob Ippolito

unread,
Dec 4, 2006, 11:01:59 AM12/4/06
to troels knak-nielsen, MochiKit

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

troels knak-nielsen

unread,
Dec 4, 2006, 11:09:04 AM12/4/06
to MochiKit
Thanks.


--
troels

Reply all
Reply to author
Forward
0 new messages