Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementsByTagName return value

Tags:

javascript

dom

I want to use

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

but document.getElementsByTagName() returns an object instead of array

How to get the array?

like image 645
Dan Avatar asked Dec 28 '22 03:12

Dan


2 Answers

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.

like image 176
bobince Avatar answered Dec 31 '22 14:12

bobince


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!

like image 31
Sean Vieira Avatar answered Dec 31 '22 15:12

Sean Vieira