Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - 如何通过类名获取元素? [重复](How to get element by class name? [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

How to Get Element By Class in JavaScript?(如何在JavaScript中按类获取元素?) 10 answers(10个答案)

Using JavaScript, we can get element by id using following syntax:(使用JavaScript,我们可以使用以下语法按id获取元素:)

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?(如何按类获取元素?)   ask by TDHM translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...