HTMLCollection的获取方式
HTMLCollection是一个由DOM元素组成的动态的集合,它可以通过以下几种方式获取:
- document.getElementsByTagName():通过标签名获取,返回值为HTMLCollection对象;
- document.getElementsByName():通过元素的name属性获取,返回值为HTMLCollection对象;
- document.getElementsByClassName():通过元素的class属性获取,返回值为HTMLCollection对象;
- document.querySelectorAll():通过CSS选择器获取,返回值为NodeList对象;
HTMLCollection的遍历方法
HTMLCollection对象可以通过以下几种方式进行遍历:
- for循环:通过length属性获取集合的长度,使用for循环遍历;
var htmlCollection = document.getElementsByTagName('div'); for(var i=0; iforEach():使用forEach()方法遍历; var htmlCollection = document.getElementsByTagName('div'); htmlCollection.forEach(function(element){ console.log(element); });for...in循环:使用for...in循环遍历; var htmlCollection = document.getElementsByTagName('div'); for(var item in htmlCollection) { console.log(htmlCollection[item]); }HTMLCollection的应用场景
HTMLCollection对象主要用于获取页面上的一组元素,可以用于以下几种场景:
- 获取页面上的一组元素,并对其进行操作,如添加/移除类名,添加/移除事件等;
var divs = document.getElementsByTagName('div'); for(var i=0; i获取页面上的一组元素,并获取其中某些属性; var divs = document.getElementsByTagName('div'); for(var i=0; i获取页面上的一组元素,并对其进行排序; var divs = document.getElementsByTagName('div'); divs.sort(function(a, b){ if(a.getAttribute('data-order') < b.getAttribute('data-order')) { return -1; } else if(a.getAttribute('data-order') > b.getAttribute('data-order')) { return 1; } else { return 0; } });