为什么document.getElementsByClassName(“ className”)返回对象 [英] why document.getElementsByClassName("className") returns object

查看:134
本文介绍了为什么document.getElementsByClassName(“ className”)返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我选择了一些dom对象:

I have a some dom objects that are selected with :

 var elems = document.getElementsByClassName("royal") ;

以及其他对象

var collapsedElems =  document.getElementsByClassName("collapsed");

我的问题是在我尝试使用数组concat()方法连接元素和崩溃元素时发生的

my problem occured when i tried to concat elems and collapsedElems with array concat() method

 elems.concat(collapsedElems) 

,但是返回类型 getElementsByClassName()不是数组,实际上它是
对象。我在Chrome控制台上使用typeof运算符对其进行了检查。这对我来说似乎很奇怪,我如何才能将这两组对象结合在一起。 ?

but the return type of getElementsByClassName() is not array actually it is object. I checked it at chrome console with typeof operator. that seems weird to me how can i combine this two group of object. ?

推荐答案

getElementsByClassName()返回 HTMLcollection 对象,它类似于数组,但实际上不是数组,因此您不能使用返回的值调用数组方法。

getElementsByClassName() returns an HTMLcollection object which is similar to an array but not really an array so you can't call array methods using the returned value.

一个hack是与 .call()一起使用Array的原型方法 / .apply()将返回的对象作为上下文传递。

One hack is to use Array's prorotype methods along with .call()/.apply() to pass the returned object as the context.

var elems = document.getElementsByClassName("royal") ;
var collapsedElems =  document.getElementsByClassName("collapsed");
var earray = Array.prototype.slice.call(elems, 0);
var concatenated = earray.concat.apply(earray, collapsedElems) ;
console.log(concatenated)

演示:小提琴

这篇关于为什么document.getElementsByClassName(“ className”)返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆