Blogger Information
Blog 27
fans 1
comment 2
visits 90500
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
获取DOM元素常见API和遍历方法
          
Original
523 people have browsed it
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport"
  6. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>11.7作业</title>
  9. <!-- 作业内容:
  10. 1. 实例演示二个获取元素的api
  11. 2. 实例演示dom常用的遍历方法-->
  12. </head>
  13. <body>
  14. <h3>1. 实例演示二个获取元素的api</h3>
  15. <div class="list">
  16. <li>item-1</li>
  17. <li>item-2</li>
  18. <li>item-3</li>
  19. <li>item-4</li>
  20. <li>item-5</li>
  21. </div>
  22. <h3> 2. 实例演示dom常用的遍历方法</h3>
  23. <pre>[...类数组] 转为数组
  24. forEach遍历</pre>
  25. <script>
  26. // 获取第3个元素的文本
  27. let list3 = document.querySelector(".list>li:nth-of-type(3)");
  28. console.log('获取第3个元素: '+list3.textContent)
  29. // 获取第1个元素 firstElementChild的文本
  30. let list1 = document.querySelector('.list>li:first-child');
  31. // textContent 获取该元素的文本
  32. console.log('获取第1个元素: '+list1.textContent)
  33. // 获取最后一个元素的文本
  34. let last = document.querySelector('.list>li:last-of-type')
  35. console.log('获取最后一个元素: '+last.textContent)
  36. // 2. 实例演示dom常用的遍历方法
  37. let arr = document.querySelector('.list')
  38. // 获取所有的子节点 childNodes
  39. // 注意:childNodes会包含空格换行等
  40. console.log("childNodes会包含空格换行",arr.childNodes)
  41. // 获取所有的元素节点
  42. console.log('获取所有的元素节点',arr.children)
  43. // 遍历
  44. // 遍历的每个li 的颜色设置为蓝色
  45. ;[...arr.children].forEach(function (li){li.style.color='blue'})
  46. // 打印每个li出来
  47. ;[...arr.children].forEach(function (li){console.log('打印遍历出来的li:',li.textContent)})
  48. // console.log(typeof [...arr.children])
  49. </script>
  50. </body>
  51. </html>

运行结果:

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