首页 > 语言 > JavaScript > 正文

用原生JS获取CLASS对象(很简单实用)

2024-05-06 16:09:40
字体:
来源:转载
供稿:网友
这篇文章主要介绍了如何用原生JS获取CLASS对象,看过dom编程艺术的朋友或许会知道的
 
 

听说是最常用。。。。我是看了dom编程艺术想到的。

 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4.  
  5. <head>  
  6.  
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  8.  
  9. <title>无标题文档</title>  
  10.  
  11. <style>  
  12.  
  13. .ca{background-color:red; padding:20px;}  
  14.  
  15. .js{ border:1px solid #00F; padding:10px;}  
  16.  
  17. </style>  
  18.  
  19. </head>  
  20.  
  21.  
  22. <body>  
  23.  
  24. <div class="ca">  
  25.  
  26. sss  
  27.  
  28. </div>  
  29.  
  30. <div class="js" id="as">  
  31.  
  32. </div>  
  33.  
  34. <div class="bd">  
  35.  
  36. </div>  
  37.  
  38. <div class="ca">  
  39.  
  40. </div>  
  41.  
  42. </body>  
  43.  
  44. </html>  
  45.  
  46. <script>  
  47.  
  48. function getElementsClass(classnames){  
  49. var classobj= new Array();//定义数组  
  50.  
  51. var classint=0;//定义数组的下标  
  52.  
  53. var tags=document.getElementsByTagName("*");//获取HTML的所有标签  
  54.  
  55. for(var i in tags){//对标签进行遍历  
  56.  
  57. if(tags[i].nodeType==1){//判断节点类型  
  58.  
  59. if(tags[i].getAttribute("class") == classnames)//判断和需要CLASS名字相同的,并组成一个数组  
  60.  
  61. {  
  62.  
  63. classobj[classint]=tags[i];  
  64.  
  65. classint++;  
  66.  
  67. }  
  68.  
  69. }  
  70.  
  71. }  
  72.  
  73. return classobj;//返回组成的数组  
  74.  
  75. }  
  76.  
  77.  
  78. //以下就是测试了  
  79.  
  80. var a=getElementsClass("ca");  
  81.  
  82. a[0].onclick=function(){alert("我们来了");}  
  83.  
  84. a[1].innerHTML='我们来了';  
  85.  
  86. </script> 
?
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表