Javakid Javakid - 1 month ago 5
Javascript Question

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

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

var $dataTable = $('#' + tabId + ' > div.container > div.dataTableContainer > table.dataTable');


But one friend of mine told me that it will be more efficient when using
Implementation 2 as below:

var dataTable = $('#' + tabId).find('table.dataTable');


Referenced to other question, I found the Implementation 2 may be less efficient than:

var $dataTable = $('#' + tabId + ' div.container div.dataTableContainer table.dataTable');


But will Implementation 2 be more efficient than Implementation 1?

Answer

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>

Comments