Making a short alias for document.querySelectorAll

前端 未结 9 1627
面向向阳花
面向向阳花 2020-12-12 14:48

I\'m going to be running document.querySelectorAll() a whole lot, and would like a shorthand alias for it.

var queryAll = document.querySelectorAll

queryAll         


        
相关标签:
9条回答
  • 2020-12-12 15:35
    function $(selector, base = null) {
      base = (base === null) ? document : base;
      return base.querySelector(selector);
    }
    
    function $$(selector, base = null) {
      base = (base === null) ? document : base;
      return base.querySelectorAll(selector);
    }
    

    Why not simplier ??? :

    let $ = (selector, base = document) => {
      let elements = base.querySelectorAll(selector);
      return (elements.length == 1) ? elements[0] : elements;
    }
    
    0 讨论(0)
  • 2020-12-12 15:36

    This would work, you need to invoke the alias using call() or apply() with the appropriate context.

    func.call(context, arg1, arg2, ...) 
    func.apply(context, [args]) 
    
    var x = document.querySelectorAll;
    x.call(document, 'body');
    x.apply(document, ['body']);
    
    0 讨论(0)
  • 2020-12-12 15:46

    This seems to work:

    var queryAll = document.querySelectorAll.bind(document);
    

    bind returns a reference to the querySelectorAll 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:

    var query = document.querySelector.bind(document);
    var queryAll = document.querySelectorAll.bind(document);
    var fromId = document.getElementById.bind(document);
    var fromClass = document.getElementsByClassName.bind(document);
    var fromTag = document.getElementsByTagName.bind(document);
    
    0 讨论(0)
提交回复
热议问题