The following code does not work. Is it something wrong?
<html>
<body>
<div></div>
<div></div>
<div></div>
<span></span>
<span></span>
<script type="text/javascript">
var i = document.getElementsByTagName("div");
var j = document.getElementsByTagName("span");
i = i.concat(j) ;
alert(i.length);
</script>
</body>
</html>
I see. Thanks Raffles and pmw57!
That’s because concat() is an Array method. i and j are not arrays, they are HTML Collections, which are objects that are “array-like” (you can loop through them, they have a length) but are not arrays (they don’t share many of the methods and properties arrays have).
If’ you really need them in a single collection, create an empty array and then loop through i and j, copying the items into your array.
You can also convert the array-like collection in to actual arrays by using splice, before performing the concat.
Something like the following should do the trick.
var i = document.getElementsByTagName("div");
i = Array.prototype.splice.call(i, 0, 0);
var j = document.getElementsByTagName("span");
j = Array.prototype.splice.call(j, 0, 0);
i = i.concat(j);