最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.getElementsByTagName return value - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

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!

发布评论

评论列表(0)

  1. 暂无评论