Blogger Information
Blog 119
fans 3
comment 1
visits 94537
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
自定义方法通过类名获取对象集合
赵大叔
Original
636 people have browsed it

实例代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .one {
  10. width:300px;
  11. height:300px;
  12. background-color:red;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div class="one">hhhhhhhhh</div>
  18. <div class="one three">eeeeeeeeeeee</div>
  19. <div class="one two">llllllllllllll</div>
  20. <div class="one two three">pppppppppppp</div>
  21. <h3 class="one">11111111111111</h3>
  22. <h3>2222222222222</h3>
  23. <p class="one">33333333333333</p>
  24. </body>
  25. </html>
  26. <script>
  27. var ones = gclass("one");
  28. console.log(ones);
  29. for(var i = 0; i < ones.length; i++) {
  30. ones[i].style.backgroundColor = "green";
  31. }
  32. // 通过类名获取所有元素的方法
  33. function gclass(className, tagName) {
  34. // var alltags = document.all;
  35. var alltags = document.getElementsByTagName(tagName || "*");
  36. var arr = new Array();
  37. for(let i = 0; i < alltags.length; i++) {
  38. // one two
  39. // split把一个字符串分割成字符串数组:
  40. var one = className.split(" ");
  41. var two = alltags[i].className.split(" ");
  42. if(isHasArray(one, two)) {
  43. arr[arr.length] = alltags[i];
  44. }
  45. }
  46. //返回所有类元素集合
  47. return arr;
  48. }
  49. // 判断一个数组中的所有元素是否在另外的一个数组中存在
  50. function isHasArray(one, two) {
  51. if(two.length < one.length){
  52. return false;
  53. }
  54. var flag = 0;
  55. for(let i=0; i<one.length; i++) {
  56. for(let j=0; j<two.length; j++) {
  57. if(one[i]==two[j]){
  58. flag++;
  59. break;
  60. }
  61. }
  62. }
  63. return flag == one.length;
  64. }
  65. </script>

结果展示

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post