0

I was searching for a simple click event script without the use of jQuery, and found some usefull code. With this I created my own variant of this code, which works, but there is one thing I don't get

[].forEach.call(document.querySelectorAll("a"), function (el) {
    el.addEventListener("click", function (ev) {
        ev.preventDefault();
        this.style.backgroundColor = "grey";
    })
});

This code grabs all <a>-elements on the webpage and adds a click event which changes the background colour to gray.

However, I don't get why forEach.call() executes while the array [] is empty.

Could someone explain how this works?

Broxzier
  • 2,909
  • 17
  • 36
  • 1
    Just a couple notes on performance...querySelectorAll() returns a live node list, so it reruns the query every time you access it. You'd be better off converting it to an array first before using forEach. Also, if you want to style links on click, you could always just use a:active in CSS. –  Jun 13 '13 at 12:41
  • The styling of links was done so I could run it in the web console on any page. – Broxzier Jun 13 '13 at 12:42
  • @Broxzier Fair enough :) –  Jun 13 '13 at 12:44

2 Answers2

3

function.call() runs a function with a different this.

Your code creates an empty array to get at the forEach method (it would be better to write Array.prototype.forEach, then calls call() to call it on the array-like NodeList.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

Although [] is an array, we're using the prototype function forEach exposed on this type.

This is a shorthand for using Array.prototype.forEach.call();

Sparko
  • 735
  • 6
  • 15