Lightweight alternative to jQuery for class / id selecting

前端 未结 6 1307
半阙折子戏
半阙折子戏 2020-12-31 07:42

Let\'s say I want to build a non-dependent javascript framework/script. Is there a way to utilize jQuery\'s amazing class and element selecting functionality



        
6条回答
  •  一个人的身影
    2020-12-31 08:15

    In everything but IE6 and IE7, you can use document.querySelectorAll or someElement.querySelectorAll to perform similar selection functionality.

    Update more details:

    It looks like ZeptoJS does the following. This uses quick functions for $$(document, '#myid'), $$(document, '.myclass'), $$(document, 'div') and slow searches for $$(document, 'div > .myclass')

    var classSelectorRE = /^\.([\w-]+)$/,
        idSelectorRE = /^#([\w-]+)$/,
        tagSelectorRE = /^[\w-]+$/;
    
    $$ = function(element, selector){
      var found;
      return (element === document && idSelectorRE.test(selector)) ?
        ( (found = element.getElementById(RegExp.$1)) ? [found] : [] ) :
        Array.prototype.slice.call(
          classSelectorRE.test(selector) ? element.getElementsByClassName(RegExp.$1) :
          tagSelectorRE.test(selector) ? element.getElementsByTagName(selector) :
          element.querySelectorAll(selector)
        );
    }
    

提交回复
热议问题