Making a short alias for document.querySelectorAll

前端 未结 9 1656
面向向阳花
面向向阳花 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:33

    Here is my take on it. If the selector has multiple matches, return like querySelectorAll. If ony one match is found return like querySelector.

    function $(selector) {
      let all = document.querySelectorAll(selector);
      if(all.length == 1) return all[0];
      return all;
    }
    
    let one = $('#my-single-element');
    let many = $('#multiple-elements li');
    

    2019 update

    Today I made a new take on the problem. In this version you can also use a base like this:

    let base = document.querySelectorAll('ul');
    
    $$('li'); // All li
    $$('li', base); // All li within ul
    

    Functions

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

提交回复
热议问题