for of loop querySelectorAll

前端 未结 9 797
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2020-12-11 03:02

    The docs are correct, but I wouldn't call this a bug. Rather it's a "not yet implemented feature".

    There is no standard for this, and there is still active discussion on how the DOM should integrate with ES6. Notice that it is clear that querySelectorAll should return something iterable which can be used in a for of loop (as the common expectation demands), but it's not clear how that should happen (Let NodeList implement the Iterable interface? Let some Elements collection subclass Array?).

    0 讨论(0)
  • 2020-12-11 03:04

    Edit: This is shipping in Chrome 51.

    Jake Archibald posted a simple fix:

    NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]
    

    And for of loops.

    0 讨论(0)
提交回复
热议问题