获取具有特定CSS类的HTML文档中的所有元素 [英] Get All Elements in an HTML document with a specific CSS Class

查看:187
本文介绍了获取具有特定CSS类的HTML文档中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript在特定CSS类的HTML文档中获取所有元素的数组的最佳方法是什么?

What's the best way to get an array of all elements in an html document with a specific CSS class using javascript?

现在没有JavaScript框架,我可以循环所有的元素,并自己手动检查。

No javascript frameworks like jQuery allowed here right now, and I could loop all the elements and check them manually myself. I'm hoping for something a little more elegant.

推荐答案

下面的答案现在推送四岁,所以值得注意本地浏览器对 getElementsByClassName()的支持 已获得很多。但是如果你必须支持旧的浏览器,那么...

The below answer is now pushing four years old, so it's worth noting that native browser support for getElementsByClassName() has gotten a lot better. But if you must support older browsers, then...

使用一个已经写好的浏览器。大多数主要的JS库包括某种形式或另一种,但如果你不使用其中之一,那么我可以推荐罗伯特·尼曼的优秀实施:

Use one that's already been written. Most major JS libraries include one in some form or another, but if you aren't using one of them then i can recommend Robert Nyman's excellent implementation:

http://code.google.com/p/getelementsbyclassname/

http://www.robertnyman.com/2008/05 / 27 / the-ultimate-getelementsbyclassname-anno-2008 /

只有太多的方法缓慢和有问题的来证明自己编写自己的实现。

There are just too many ways to make this (conceptually-simple) routine slow and buggy to justify writing your own implementation at this point.

这篇关于获取具有特定CSS类的HTML文档中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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