for of loop querySelectorAll

前端 未结 9 796
忘了有多久
忘了有多久 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:40

    This is what I do, for a different approach

    Array.prototype.forEach.call(document.querySelectorAll("input[type=checkbox]"),function(ele,idx)
    {
        ele.checked = true;
    }
    

    good from IE9 and above

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

    Native Symbol.iterator support for NodeList was added to the WHATWG's DOM spec in 2014.

    Unfortunately, Chrome 51 is the first version of Chrome to support it, and its Beta has only just been released at the time of writing this answer. Also, there's no support in any version of Internet Explorer or Edge.

    To add Symbol.iterator support for NodeList in all browsers to your code, just use the following polyfill :

    NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    
    0 讨论(0)
  • 2020-12-11 02:50

    Since I've successfully used for..of in Gecko to iterate NodeLists, it seems this is a browser bug, or at least a browser lack.

    Actual working code from a userscript I currently use:

    let llnk = document.querySelectorAll("div#threadlist a.threadtitle_unread");
    for (let lnk of llnk) {
        //...
    }
    

    (This also uses let, but that's another story.)

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

    I had this problem. Turns out mine was caused by calling Promise.all() with parameters instead of an array. For example:

    Before: Promise.all(p1, p2)

    After: Promise.all([p1, p2])

    Hope this helps someone.

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

    Here's yet another solution for the modern age:

    [...document.querySelectorAll("input[type=checkbox]")].forEach(node => {
         node.textContent = "foo";
    });
    

    This takes advantage of the spread operator which is supported in Google Chrome 46+, Firefox 16+, and Edge, and just for fun the arrow function.

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

    Try utilizing Array.prototype.entries()

    var list = [].entries.call(document.querySelectorAll("input[type=checkbox]"));
    
    for (item of list) {
      item[1].checked = true;
    };
    <input type="checkbox" /><input type="checkbox" />

    You could also use Array.prototype.values()

    var list = [].values.call(document.querySelectorAll("input[type=checkbox]"));
    
    for (item of list) {
      item.checked = true;
    };
    <input type="checkbox" /><input type="checkbox" />

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