I want to use
document.getElementsByTagName('input').concat( some_array )
but document.getElementsByTagName()
returns an object
instead of array
How to get the array?
I want to use
document.getElementsByTagName('input').concat( some_array )
but document.getElementsByTagName()
returns an object
instead of array
How to get the array?
Share Improve this question edited Jan 5, 2011 at 10:32 Dan asked Dec 22, 2010 at 19:56 DanDan 58k44 gold badges122 silver badges162 bronze badges2 Answers
Reset to default 7Unfortunately to do this fully reliably you need to do it manually, eg:
function toArray(arraylike) {
var array= new Array(arraylike.length);
for (var i= 0, n= arraylike.length; i<n; i++)
array[i]= arraylike[i];
return array;
}
toArray(document.getElementsByTagName('img')).concat(...)
Whilst you often can get away with using Array.prototype.somearraymethod.call
as in Sean's answer, this may fail on browsers where the NodeList
object returned by getElementsByTagName
is a ‘host object’.
ECMAScript defines that calling methods on the Array.prototype
has to work for native-JS objects with a length
and integer properties, and for the arguments
object, but it makes no guarantees for host objects. As with almost everything involving host objects, the browser is free to screw you over however it likes.
If you don't need to support IE versions less than or equal to 7* then use slice()
:
Array.prototype.slice.call(
document.getElementsByTagName('img')).concat(some_array)
*
Thanks bobince!