Element in DOM

JavaScript performance comparison

Test case created by Joshua Inkenbrandt

Info

Fastest way to tell if an object is in the DOM.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div>
  <div>
    <ul>
      <li id='elementInDOM'></li>
    </ul>
  </div>
</div>
<script>
Benchmark.prototype.setup = function() {
    var elements = [
        [function() { return document.createElement('div') }, false],
        [function() { return document.getElementById('elementInDOM') }, true]
    ];
   
    var runTest = function(func) {
        for (var i = 0, l = elements.length; i < l; i++) {
            var method = elements[i][0];
            var el = method();
            if (!el) {
                throw new Error(i + " doesn't have an element")
            }
            if (func(el) !== elements[i][1]) {
                throw new Error("Test "+ i +" doesn't work!");
            }
        }
    }
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
By ID
runTest(function(el) {
   if (el.id) {
       return !!document.getElementById(el.id)
   }
   el.setAttribute('id', 'finder');
   result = !!document.getElementById('finder');
   el.removeAttribute('id');
   return result;
});
pending…
Up the parent chain
runTest(function(el) {
    while (el = el.parentNode) {
        if (el === document) {
            return true;
        }
    }
    return false;
});
pending…
By ID jQuery
runTest(function(el) {
    el = $(el);
    if (el.attr('id')) {
        return $('#' + el.attr('id')).length > 0;
    }
    el.attr('id', 'finder');
    var result = $('#' + el.attr('id')).length > 0;
    el.removeAttr('id');
    return result;
});
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment