如何通过类名获取元素? [英] How to get element by class name?
问题描述
使用JavaScript,我们可以使用以下语法获取元素id:
var x = document.getElementById(by_id );
我尝试继续按类获取元素:
var y = document.getElementByClass(by_class);
但是导致错误:
getElementByClass不是函数
如何获取元素class?
DOM函数的名称实际上是 getElementsByClassName
不是 getElementByClassName
,只是因为页面上的多个元素可以具有相同的类,因此:元素
。 p>
这个返回值将是一个NodeList实例,或 NodeList
的超集(FF,例如返回一个 HTMLCollection
的实例)。无论如何:返回值是一个类似数组的对象:
var y = document.getElementsByClassName('foo');
var aNode = y [0];
如果由于某种原因您需要返回对象作为数组,你可以轻松地做到这一点,因为它的魔法长度属性:
var arrFromList = Array.prototype.slice.call(y) ;
//或根据AntonB的评论:
var arrFromList = [] .slice.call(y);
由于yckart建议 querySelector('。foo')$ c $根据caniuse.com的说法,c>和
querySelectorAll('。foo')
将是更好的,尽管如此,他们确实更好的支持(93.99%对87.24%) :
Using JavaScript, we can get element by id using following syntax:
var x=document.getElementById("by_id");
I tried following to get element by class:
var y=document.getElementByClass("by_class");
But it resulted into error:
getElementByClass is not function
How can I get an element by its class?
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
.
The return value of this will be a NodeList instance, or a superset of the NodeList
(FF, for instance returns an instance of 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:
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:
- querySelector(all)
- getElementsByClassName
- Don't use w3schools to learn something
- Refer to MDN for accurate information
这篇关于如何通过类名获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!