Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a short alias for document.querySelectorAll

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?

like image 784
mikemaccana Avatar asked Nov 14 '12 17:11

mikemaccana


People also ask

What can I use instead of document querySelector?

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.

What does querySelectorAll mean?

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.

What does document querySelectorAll take as its argument and what does it return?

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.


2 Answers

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); 
like image 142
Sunday Ironfoot Avatar answered Sep 21 '22 21:09

Sunday Ironfoot


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>
like image 42
aloisdg Avatar answered Sep 19 '22 21:09

aloisdg