for of loop querySelectorAll

前端 未结 9 823
忘了有多久
忘了有多久 2020-12-11 02:29

Mozilla states that \"for of loops will loop over NodeList objects correctly\". (source: https://developer.mozilla.org/en-US/docs/Web/API/NodeList) However, this doesn\'t wo

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 02:59

    You can use Array.from

    let _list = document.querySelectorAll('input[type=checkbox]');
    
    let list = Array.from(_list);
    
    for (let item of list) {
      //... just like an array
      item.checked = true
    }
    

    or more shortly

    let list = document.querySelectorAll('input[type=checkbox]');
    
    for (let item of Array.from(list)) {
      item.checked = true
    }
    

    Important note Array.from was introduced in Chrome 45 source.

提交回复
热议问题