博主信息
博文 21
粉丝 0
评论 0
访问量 16893
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
js 自定义获取指定类名的标签集合
中天行者
原创
762人浏览过
  1. <!DOCTYPE html>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Title</title>
  7. </head>
  8. <body>
  9. <div class="one"> one </div>
  10. <br>
  11. <h1 class="three">three</h1>
  12. <form class="two" action="">
  13. <i class="two a" id="">two a</i><br>
  14. <b class="two b">two b</b><br>
  15. <b class="two">two</b><br>
  16. <b class="two c">two c</b><br>
  17. <b class="two d a c">two d a c</b><br>
  18. <string class="two e ">two e</string><br>
  19. <a href="javascript:;" class="three h" onclick="getClassNames()">点击获取</a>
  20. </form>
  21. <script>
  22. function getClassName(tag ='', classNames='' ) {
  23. var returnTags=[];
  24. var tags;
  25. if(tag===''){
  26. tags = document.getElementsByTagName("*");
  27. }else {
  28. tags = document.getElementsByTagName(tag);
  29. }
  30. var c=classNames.split('|');
  31. if(c .length===1 && c[0]===''){
  32. alert('类名不能为空');
  33. return false
  34. }
  35. for (var i =0;i<tags.length;i++){
  36. var c1=tags[i].className.split(' ');
  37. if( c .length===1){
  38. //遍历每个标签
  39. c1.forEach(function (v,index) {
  40. if (v === c[0]) {
  41. returnTags.push(tags[i])
  42. }
  43. })
  44. }else {
  45. //遍历每个标签
  46. c1.forEach(function (v,index) {
  47. // 遍历每个需要查询的每个类名
  48. if(!returnTags.includes(tags[i])){
  49. c.forEach(function (value) {
  50. if(!returnTags.includes(tags[i])) {
  51. if (v === value) {
  52. returnTags.push(tags[i]);
  53. }
  54. }
  55. })
  56. }
  57. })
  58. }
  59. }
  60. return returnTags;
  61. }
  62. function getClassNames(){
  63. var tt = prompt('请输入查询的标签,全部标签请用*代替',"*");
  64. var cc = prompt('请输入查询的类名多个用 | 隔开,目前已定义的类名 one two three a b c d e ');
  65. console.log(getClassName(tt, cc));
  66. }
  67. </script>
  68. </body>
  69. </html>
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学