Is it more efficient to use find() rather than > for child selector in jQuery?

后端 未结 2 1025
轻奢々
轻奢々 2020-12-03 17:45

In jQuery, I thought it will be more efficient to find a child DOM with a specific selector with Implementation 1 as below:

var $dataTable =         


        
相关标签:
2条回答
  • 2020-12-03 17:55

    My guess:

    Under the hood $('#XXX whatever') does a native document.queryselectorAll(), which will check all of the elements within the document to see if they match '#xxx whatever'

    $('#XXX').find('whatever') first does a document.getElementById('XXX'), finding the element with id="XXX" and then does a queryselectorAll() within that element, so has fewer child elements to test and see if they match 'whatever'

    But this guess is completely negated by real data - see the answer by @guest271314

    0 讨论(0)
  • document.querySelector() with direct descendant selector > is fastest, .find() is slowest.

    var tabId = "abc";
    
    console.time(".find()");
    var $dataTable = $('#' + tabId).find('table.dataTable');
    console.timeEnd(".find()");
    
    console.time("jQuery(), >");
    var $dataTable = $('#' + tabId + ' > div.container > div.dataTableContainer > table.dataTable');
    console.timeEnd("jQuery(), >");
    
    console.time("document.querySelector()");
    var $dataTable = document.querySelector('#' + tabId + ' div.container div.dataTableContainer  table.dataTable');
    console.timeEnd("document.querySelector()");
    
    console.time("document.querySelector(), >");
    var $dataTable = document.querySelector('#' + tabId + ' >  div.container > div.dataTableContainer > table.dataTable');
    console.timeEnd("document.querySelector(), >");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="abc">
      <div class="container">
        <div class="dataTableContainer">
          <table class="dataTable">
            <tbody>
              <tr>
                <td></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    
    </div>

    0 讨论(0)
提交回复
热议问题