ASCII码 ASCII码

浏览器中的JS和获取dom元素

发布于:2022-06-13 10:45:41  栏目:技术文档
  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. <script src="demo7.js"></script>
  8. <title>浏览器中的JS</title>
  9. </head>
  10. <body>
  11. <!-- js的工作环节/宿主环境:浏览器和服务器node.js -->
  12. <!-- 1.事件属性,写到元素的事件属性 -->
  13. <button onclick="console.log('hello world');">按钮1</button>
  14. <button onclick="setBg(this)">按钮2</button>
  15. <!-- 获取dom元素 -->
  16. <ul class="list">
  17. <li class="item">item1</li>
  18. <li class="item">item2</li>
  19. <li class="item">item3</li>
  20. <li class="item">item4</li>
  21. <li class="item">item5</li>
  22. </ul>
  23. <script>
  24. // TODDD 获取一组 querySelectorALL(css选择器)
  25. console.log(document);
  26. const items = document.querySelectorAll(".list > .item");
  27. console.log(items);console.log(document);
  28. for(let i = 0;i < items.length; i++){
  29. items[i].style.color = "red";
  30. }
  31. // TODDD 获取一个 querySelector(css选择器)
  32. const first = document.querySelector(".list > .item");
  33. console.log(first);
  34. first.style.backgroundColor = "yellow";
  35. const third = document.querySelector(".list > .item:nth-of-type(3)");
  36. console.log(third);
  37. third.style.backgroundColor = "yellow";
  38. </script>
  39. </body>
  40. </html>
相关推荐
阅读 +