isOrIn alternatives
Testing different methods of checking whether an element is or is in another element
Date tested:
7 years ago
User agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Test name
Executions per second
is() or contains()
0.0 Ops/sec
== or contains()
637649.7 Ops/sec
!!closest.length
247646.8 Ops/sec
== and parentNodes
701283.8 Ops/sec
Benchmark definition (click to collapse):
HTML Preparation code:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.0.min.js"></script>
Script Preparation code:
//Add 100,000 elements var frag = document.createDocumentFragment(); for (var i=0; i<10; i++){ var outDiv = document.createElement('div'); for (var j=0; j<100; j++){ var midDiv = document.createElement('div'); for (var k=0; k<100; k++){ var inDiv = document.createElement('div'); if(i==6 && j==60){ if(k==60) inDiv.id="one"; else if(k==61) inDiv.id="two"; } midDiv.appendChild(inDiv) } outDiv.appendChild(midDiv) } frag.appendChild(outDiv); } document.body.appendChild(frag); var innerOne = document.getElementById('one');
Tests:
is() or contains()
var found = $.is(document.body,innerOne) || $.contains(document.body,innerOne);
== or contains()
var found = document.body==innerOne || $.contains(document.body,innerOne);
!!closest.length
var found = !!$(innerOne).closest(document.body).length;
== and parentNodes
var found = false; var container = document.body; if(innerOne===document.body){ found=true } else{ var pointer = innerOne; var parent = pointer.parentNode; while(parent && pointer!==container){ if(parent === container){ found=true; break; } pointer = parent; parent = pointer.parentNode; } }
Open this result on MeasureThat.net