Skip to content Skip to sidebar Skip to footer

Document.getelementsbytagname Return Value

I want to use document.getElementsByTagName('input').concat( some_array ) but document.getElementsByTagName() returns an object instead of array How to get the array?

Solution 1:

Unfortunately to do this fully reliably you need to do it manually, eg:

functiontoArray(arraylike) {
    vararray= newArray(arraylike.length);
    for (var i= 0, n= arraylike.length; i<n; i++)
        array[i]= arraylike[i];
    returnarray;
}

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.

Solution 2:

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!

Post a Comment for "Document.getelementsbytagname Return Value"