<html>
<head>
<title>forEach vs getElementsByTagName</title>
<script type="text/javascript" src="res/mochikit.js"></script>
</head>
<body>
<div id="container">
<span> </span>
<span> </span>
<span> </span>
<span> </span>
<span> </span>
<span> </span>
<span> </span>
<span> </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
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