The name of the DOM function is actually getElementsByClassName
, not getElementByClassName
, simply because more than one element on the page can have the same class, hence: Elements
.(DOM函数的名称实际上是getElementsByClassName
,而不是getElementByClassName
,仅仅是因为页面上的多个元素可以具有相同的类,因此: Elements
。)
The return value of this will be a NodeList instance, or a superset of the NodeList
(FF, for instance returns an instance of HTMLCollection
).(这一返回值将是一个节点列表实例,或所述的一个超集NodeList
(FF,例如返回的一个实例HTMLCollection
)。) At any rate: the return value is an array-like object:(无论如何:返回值是一个类似数组的对象:)
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:(如果由于某种原因需要返回对象作为数组,则由于其不可思议的length属性,可以轻松地做到这一点:)
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo')
and querySelectorAll('.foo')
would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:(正如yckart所建议的那样,根据caniuse.com的说法, querySelector('.foo')
和querySelectorAll('.foo')
会更好,因为它们的确受到了更好的支持(93.99%vs 87.24%):)
querySelector(all)(querySelector(全部))
getElementsByClassName(getElementsByClassName)
Don't use w3schools to learn something(不要使用w3schools学习东西)
Refer to MDN for accurate information(有关准确信息,请参考MDN)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…