jQuery Element Removed?

JavaScript performance comparison

Revision 15 of this test case created by Eamon Nerbonne

Info

Checks if a DOM element has been removed; returns true if in DOM, false if removed.

Updated to jquery 1.9.1.

2013-06-12: - added fast isInDom function - now verifies whether the alternatives actually work too in cleanup. (+prevent dead code elimination).

Preparation code

<div id="element"></div><div id="tests"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var isInDom = (function(){ //by Eamon Nerbonne
  var root = document.documentElement;
  return function f(el) {
    return el === root || !!el && f(el.parentElement);
  }
})();

var removed = $('#element').remove();
var inDom = $('#tests');
</script>
<script>
Benchmark.prototype.setup = function() {
    OK = false
};

Benchmark.prototype.teardown = function() {
    if(!OK) throw OK;
};
</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
closest 'html' inDom
OK = inDom.closest('html')[0];
pending…
closest 'html' removed
OK = !removed.closest('html')[0];
pending…
jQuery.contains inDom
OK = jQuery.contains(document.documentElement, inDom[0]);
pending…
jQuery.contains removed
OK = !jQuery.contains(document.documentElement, removed[0]);
pending…
jQuery.contains short inDom
OK = jQuery.contains(document, inDom[0]);
pending…
jQuery.contains short removed
OK = !jQuery.contains(document, removed[0]);
pending…
isInDom inDom
OK = isInDom(inDom[0]);
pending…
isInDom removed
OK = !isInDom(removed[0]);
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