javascriptnative-methods

Making a short alias for document.querySelectorAll


I'm running document.querySelectorAll() frequently, and would like a short 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?


Solution

  • 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);