1.classlist

  1. classList对象有下列方法:
  2. add():增加一个 class
  3. remove():移除一个 class
  4. contains():检查当前元素是否包含某个 class
  5. toggle():将某个 class 移入或移出当前元素。
  6. item():返回指定索引位置的 class
  1. <style>
  2. .active{
  3. background: red;
  4. }
  5. </style>
  1. <p id="p">hello world</p>
  2. <button id="btn">addClass</button>
  3. <button id="remove">removeClass</button>
  4. <button id="toggle">toggleClass</button>
  5. <!-- classList
  6. add() --添加一个class
  7. remove() --移除一个class
  8. toggle() --将某个class移出或移入某个对象
  9. contains() --检查当前元素是否包含某个class
  10. -->
  11. <script>
  12. var btn=document.getElementById("btn");
  13. var p=document.getElementById("p");
  14. var remove=document.getElementById("remove");
  15. var toggle=document.getElementById("toggle");
  16. btn.onclick=function(){
  17. p.classList.add("active") //添加
  18. }
  19. remove.onclick=function(){
  20. p.classList.remove("active") //移除
  21. }
  22. toggle.onclick=function(){
  23. p.classList.toggle("active") //移入/移除
  24. }
  25. </script>

2.添加元素:

2.1父元素:parentNode.prepend(),parentNode.append()

  • prepend()在父元素的第一位增加元素
  • append()在父元素的最后一位增加元素

    Tip:可添加多个,元素和文本都可以 ```javascript

    think you

    hello world

输出结果: think you 前面 hello world 后面

  1. <a name="2UDa5"></a>
  2. #### 2.2兄弟元素:before() ,after()
  3. ```javascript
  4. <p id="p">hello world</p>
  5. <script>
  6. var p=document.getElementById("p")
  7. p.before("前面")
  8. P.after("后面")
  9. </script>
  10. 输出结果:
  11. 前面
  12. hello world
  13. 后面