chaining getElementById

前端 未结 6 1705
盖世英雄少女心
盖世英雄少女心 2020-11-29 12:27

I\'ve been looking for an answer to this question but I could find none so I thought I\'d try StackOverflow.

In javascript, is this valid:

x = document

6条回答
  •  难免孤独
    2020-11-29 12:53

    This is a fast alternative based on Node.contains

    var getById = function(id, context) {
      var el = document.getElementById(id);
      return context.contains(el) ? el : null;
    }
    
    var container = document.getElementById('container-element');
    getById('my-element-id', container);
    

    The last line (profiled on latest Chrome and Firefox) performs 4x to 10x faster than jQuery's equivalent

    $('#my-element-id', container);
    

    The only good alternative is querySelector (a bit faster)

    container.querySelector('#my-element-id');
    

提交回复
热议问题