0

How does following code works?

var myNodeList = document.querySelectorAll('li'); // grabs some <li>
[].forEach.call(myNodeList, function (item) {
  // :) hooray `item` can be used here
});

Whereas ,

document.querySelectorAll('li').forEach.call(myNodeList, function (item) {
      // throws error
});

Read something - This accesses the created (empty) array’s prototype method and using call allows the NodeList to take advantage.

Any help would be appreciated.

Question is

What makes following code access the created (empty) array’s prototype method and using call allows the NodeList to take advantage

[].forEach.call(myNodeList, function (item) {
  // :) hooray `item` can be used here
});

https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/

Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79

1 Answers1

0

document.querySelectorAll('li') return array like result to apply foreach you should use Array.apply

Array.apply(null, document.querySelectorAll('li')).forEach(function(item) {
    console.log(item)
  });

fiddle

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84