getElementsByClassName
时间:2013-05-28 08:28:04
发布:admin
来源:未知
1.function getElementsByClassName(clsName,htmltag){
2. var arr = new Array();
3. var elems = document.getElementsByTagName(htmltag);
4. for ( var cls, i = 0; ( elem = elems[i] ); i++ ){
5. if ( elem.className == clsName ){ //只能取到className完全相等的情况,为考虑有多个class的情况
6. arr[arr.length] = elem;
7. }
8. }
9. return arr;
10.}
11.
12.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
13.<html xmlns="http://www.w3.org/1999/xhtml">
14.<head>
15.<title> node list </title>
16.</head>
17.<body>
18.
19.<div id="theobj">
20. <li class="aa" id="0">0</li>
21. <li class="aa" id="1">1</li>
22. <li class="aa" id="2">2</li>
23. <li class="aa" id="3">3</li>
24. <li class="aa" id="4">4</li>
25. <span class="aa">span0</span>
26. <span class="aa">span1</span>
27. <span class="aa">span2</span>
28. <span class="aa">span3</span>
29. <span class="aa">span4</span>
30.</div>
31.<div id="theobj1">
32. <li class="aa" id="10">k0</li>
33. <li class="aa" id="11">k1</li>
34. <li class="aa" id="12">k2</li>
35. <li class="aa" id="13">k3</li>
36. <li class="aa" id="14">k4</li>
37. <span class="aa" id="20">sp1an0</span>
38. <span class="aa" id="21">sp23an1</span>
39. <p class="aa" id="22">sp3an2</p>
40. <span class="aa" id="23">sp4an3</span>
41. <span class="aa" id="24">sp5an4</span>
42.</div>
43.<div class="bb cc" id="el">23 2eell 23</div>
44.
45.<script language="JavaScript">
46.function $id(id) {return document.getElementById(id);}
47.
48.var elems=document.getElementsByTagName('li');
49.
50.for (var i=0;i<elems.length ; i++ )
51.{
52. elems[i].i=i+1;
53. elems[i].onclick=function() {
54. alert(this.i+'vs'+this.innerHTML);
55. }
56.}
57.
58.alert(getElementsByClassName('aa','span','theobj1')[3].innerHTML);
59.//alert(getElementsByClassName1('aa','li')[7].innerHTML);
60.
61.//从root的节点htmltag中取含有clsName的节点组成一个数组
62.function getElementsByClassName(clsName,htmltag,root){
63. var arr = new Array();
64. var obj = document.getElementById(root);
65. var elems = obj.getElementsByTagName(htmltag);
66. for ( var cls, i = 0; ( elem = elems[i] ); i++ ){
67. if ( hasClass(clsName,elem) ) {
68. arr[arr.length] = elem;
69. }
70. }
71. return arr;
72.}
73.
74./*
75.从页面中取所有含有clsName的htmltag节点组成一个数组。
76.*/
77.function getElementsByClassName1(clsName,htmltag){
78. var arr = new Array();
79. var elems = document.getElementsByTagName(htmltag);
80. for ( var cls, i = 0; ( elem = elems[i] ); i++ ){
81. if ( hasClass(clsName,elem) ){
82. arr[arr.length] = elem;
83. }
84. }
85. return arr;
86.}
87.
88./*
89.判断对象elem中是否含有className:clsName,
90.有则返回1,否则返回0;
91.*/
92.function hasClass(clsName,elem) {
93. var re;
94. var str = elem.className;
95. re = new RegExp('(?:^|s+)' + clsName + '(?:s+|$)') ;
96. return re.test(str) ? 1 : 0 ;
97.}
98.</script>
99.</body>
100.</html>
|
关键字: |