- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title>根据类名查找对象</title>
- <script type="text/javascript">
- function getElementsByClassName(a, b) {
- if (a.getElementsByClassName) {
- return a.getElementsByClassName(b);
- } else {
- return function c(m, k) {
- if (k == null) {
- k = document;
- }
- var h = [], g = k.getElementsByTagName("INPUT"), d = g.length, l = new RegExp("(^|\\s)" + m + "(\\s|$)"), f, e;
- for (f = 0, e = 0; f < d; f++) {
- if (l.test(g[f].className)) {
- h[e] = g[f];
- e++;
- }
- }
- return h;
- }(b, a);
- }
- }
- function view(){
- var v = getElementsByClassName(document,"a");
- alert(v.length);
- alert(v[1].id);
- }
- </script>
- </head>
- <body>
- <div class="a" id=1 style="width:300px;height:300px;background:red;float:left">
- </div>
- <div class="a" id=2 style="width:300px;height:300px;background:green;float:left">
- </div>
- <div class="a" id=3 style="width:300px;height:300px;background:red;float:left">
- </div>
- <input type="button" value="查看classname为a的个数" onclick="view()"/>
- </body>
- </html>
根据类名查找对象
最新推荐文章于 2022-06-29 13:50:28 发布