当前位置:   article > 正文

js 给某个div增加class 样式(三种方式)_js给div添加class

js给div添加class

第一种:      el.setAttribute('class','abc');  

  1. <!DOCTYPE HTML>
  2. <HTML>
  3. <HEAD>
  4. <meta charset="utf-8" />
  5. <title>setAttribute('class', 'abc')</title>
  6. <style type="text/css">
  7. .abc {
  8. background: red;
  9. }
  10. </style>
  11. </HEAD>
  12. <BODY>
  13. <div id="div">test div</div>
  14. <script>
  15. var div = document.getElementById('div');
  16. div.setAttribute("class", "abc");
  17. </script>
  18. </BODY>
  19. </HTML>

第二种: el.setAttribute('className', 'abc');

  1. <!DOCTYPE HTML>
  2. <HTML>
  3. <HEAD>
  4. <meta charset="utf-8" />
  5. <title>setAttribute('className', 'abc')</title>
  6. <style type="text/css">
  7. .abc {
  8. background: red;
  9. }
  10. </style>
  11. </HEAD>
  12. <BODY>
  13. <div id="div">test div</div>
  14. <script>
  15. var div = document.getElementById('div');
  16. div.setAttribute("className", "abc");
  17. </script>
  18. </BODY>
  19. </HTML>

第三种:el.className = 'abc'; 

  1. <!DOCTYPE HTML>
  2. <HTML>
  3. <HEAD>
  4. <meta charset="utf-8" />
  5. <title>el.className = 'abc'</title>
  6. <style type="text/css">
  7. .abc {
  8. background: red;
  9. }
  10. </style>
  11. </HEAD>
  12. <BODY>
  13. <div id="div">test div</div>
  14. <script>
  15. var div = document.getElementById('div');
  16. div.className = 'abc';
  17. </script>
  18. </BODY>
  19. </HTML>

建议使用第三种方法, 其他方法可能存在浏览器兼容问题。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/767456
推荐阅读