I want to use
document.getElementsByTagName('input').concat( some_array )
but document.getElementsByTagName()
returns an object
instead of array
How to get the array?
Unfortunately 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With