Document.getElementsByTagName return value

I want to use

document.getElementsByTagName('input').concat( some_array ) 

but document.getElementsByTagName() returns object instead of array

How to get an array?

+4
javascript dom
source share
2 answers

Unfortunately, for this to be completely reliable, you need to do this manually, for example:

 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(...) 

While you can often avoid using Array.prototype.somearraymethod.call , as in Sean's answer, this may fail in browsers where the NodeList returned by getElementsByTagName is a "host object".

ECMAScript determines that invocation methods in Array.prototype should work for native-JS objects with the length and integer properties, and for the arguments object, but it does not give any guarantees for host objects. Like almost everything related to host objects, the browser is free to plunge you, but it loves.

+6
source share

If you do not need to support IE versions less than or equal to 7 *, use slice() :

 Array.prototype.slice.call( document.getElementsByTagName('img')).concat(some_array) 

* Thank bobince!

+3
source share

All Articles