I'm going to be running document.querySelectorAll() a whole lot, and would like a shorthand alias for it.
var queryAll = document.querySelectorAll
queryAll('body')
TypeError: Illegal invocation
Doesn't work. Whereas:
document.querySelectorAll('body')
Still does. How can I make the alias work?
This seems to work:
bind
returns a reference to thequerySelectorAll
function, changing the context of 'this' inside the querySelectorAll method to be the document object.The bind function is only supported in IE9+ (and all the other browsers) - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
Update: In fact you could create shortcuts to a whole range of document methods like this:
This would work, you need to invoke the alias using
call()
orapply()
with the appropriate context.