2

For funsies, I tried to create a shorthand version of document.querySelectorAll by making it usable like the way jQuery does it. Here is the code:

window.$ = document.querySelectorAll;

var links;
links = document.querySelectorAll('a'); // Works
links = $('a'); // Doesn't work

For some reason, $ isn't working even though it is a reference to document.querySelectorAll. I know that I could do this instead:

function $(selector) {
  return document.querySelectorAll(selector);
}

but I just don't understand why the first example doesn't work.

Saad
  • 49,729
  • 21
  • 73
  • 112
  • What error are you getting? – zero298 Sep 17 '15 at 02:39
  • *querySelectorAll* is an interface that expects to be called on some object that supports the interface, so it needs to have its *this* set to that object. You probably need a function anyway since you might want to provide a different root element, e.g. `function $(selector, root) { root = root || document; return root.querySelectorAll(selector);}`.. – RobG Sep 17 '15 at 02:54

1 Answers1

1

Different this variables:

document.querySelectorAll() -> `this` is document
querySelectorAll() -> `this` is window
c-smile
  • 26,734
  • 7
  • 59
  • 86
  • `window.$ = document.querySelectorAll.bind(document);` solves the problem. –  Sep 17 '15 at 02:44
  • In ES6 you can use `((w,d)=>{w.$=d.querySelectorAll.bind(d)})(window,document);` –  Sep 17 '15 at 02:52