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?
I took @David Muller's approach and one-lined it using a lambda
Example:
My solution covers the four following use cases:
The code:
In terms of parameters, the selector
s
is required, but the container element objecto
is optional.Usage:
qs("div")
: Queries the whole document for the first div, returns that elementqsa("div")
: Queries the whole document for all divs, returns a nodeList of all those elementsqs("div", myContainer)
: Queries just within the myContainer element for the first div, returns that elementqsa("div", myContainer)
: Queries just within the myContainer element for all divs, returns a nodeList of all those elementsTo make the code slightly shorter (but not quite as efficient), the
qs
code could be written as follows:The code above uses ES6 features (
let
, arrow functions and default parameter values). An ES5 equivalent is:or the equivalent shorter but less efficient ES5 version of
qs
:Below is a working demo. To ensure it works on all browsers, it uses the ES5 version, but if you're going to use this idea, remember that the ES6 version is shorter:
A common answer is to use
$
and$$
forquerySelector
andquerySelectorAll
. This alias mimics jQuery's one.Example:
The JavaScript interpreter throws an error because
querySelectorAll()
should be invoked in document context.The same error is thrown when you are trying to call
console.log()
aliased.So you need to wrap it like this:
Here is my take on it. If the selector has multiple matches, return like
querySelectorAll
. If ony one match is found return likequerySelector
.2019 update
Today I made a new take on the problem. In this version you can also use a base like this:
Functions