Sag1v Sag1v - 1 month ago 6
jQuery Question

Check the number of DOM "travels" when using a jQuery function

I would like to count and test the number of hits jQuery does when i use certain functions (reading the docs not helping much).

For example:

var $e = $('#someId');
var result = $'div');

Do we hit the dom twice? or do we use a "cached" object and got the answer already in our object?

My question is how can i count the number of hits made against the DOM?


You may try monkey-patching document methods with your own methods which count how many times they were called, i.e.

  function watchDom() {
    var originals = {};
    var domHitsCnt = 0;
    for (var method in document) { 
      if (typeof document[method] !== 'function') {
        // skip all non-function members of document object
      (function(method) {
        originals[method] = document[method]; // save original doc. method
        document[method] = function() { // replace original doc. method with the one that count calls
          return originals[method].apply(document, arguments);

    // below goes the code you want to test
    var $el = $('#d');


A fiddler example.