Blogger Information
Blog 25
fans 0
comment 0
visits 13496
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
HTML中DOM树遍历的方法及案例
安超
Original
619 people have browsed it

1. HTML DOM遍历的具体案例,在ES6中,DOM遍历的方法主要有三个:

1.向后遍历 querySelecotr 和querySelectorAll。这两个方法的参数是CSS选择符。如<p> #id,.css,div > p ,div ~ p 等
2.向前遍历 closest(),主要用来查找自身或者父级元素,只有一个。
3.DOM的元素都可以调用这两个方法。
下面用案例进行说明。
案例效果见图。
被操作的DOM元素
控制台结果。
console输出结果

  1. // 1.查找页面中属性为checked的input框
  2. let input = document.querySelectorAll(':checked');
  3. console.log(input);
  4. // 查找li元素中的第二个子元素
  5. let li = document.querySelector('li:nth-of-type(2)');
  6. console.log(li.textContent);
  7. // 查找已checked的input框的上级li元素
  8. let inputP = [...input].map(ele => ele.closest('li'));
  9. console.log(inputP);
  10. // 在已checked的input框的li中查找type=number的input框
  11. let inputN = inputP.map(ele =>ele.querySelector('*[type=number]'));
  12. console.log(inputN);
  13. // 将type=number的input框的value值取出来
  14. let inputValue = inputN.map(ele => ele.value*1);
  15. console.log(inputValue);
  16. // 直接求取type= number的input框
  17. let span = document.querySelector('[type = number]');
  18. let lisp = span.closest("li");
  19. console.log(lisp);
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!