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?
The other alternative is element. query / queryAll . These are alternative methods to querySelector and querySelectorAll that exist on DOM parent nodes. They also take selectors, except these selectors are interpreted relative to the element being queried from.
Definition and Usage The querySelectorAll() method returns all elements that matches a CSS selector(s). The querySelectorAll() method returns a NodeList. The querySelectorAll() method throws a SYNTAX_ERR exception if the selector(s) is invalid.
querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
This seems to work:
const queryAll = document.querySelectorAll.bind(document);
bind
returns a new function which works identically to the querySelectorAll
function, where the value of this
inside the querySelectorAll
method is bound to 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:
const query = document.querySelector.bind(document); const queryAll = document.querySelectorAll.bind(document); const fromId = document.getElementById.bind(document); const fromClass = document.getElementsByClassName.bind(document); const fromTag = document.getElementsByTagName.bind(document);
A common answer is to use $
and $$
for querySelector
and querySelectorAll
. This alias mimics jQuery's one.
Example:
const $ = document.querySelector.bind(document) const $$ = document.querySelectorAll.bind(document) $('div').style.color = 'blue' $$('div').forEach(div => div.style.background = 'orange')
div { margin: 2px; }
<div> test </div> <section> <div> hello </div> <div> foo </div> </section>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With