Closest vs while parent

Benchmark created on


Description

Tests whether closest or parent while loops are faster.

Preparation HTML

<block><block><block><block><block>
<div inert><div><div><div><div>
<img/>
</div></div></div></div></div>
</block></block></block></block></block>

Setup

const img = document.querySelector('img');
const div = document.querySelector('div[inert]');

function hasInert(el, parent) {
	let node = el;
	while (node && node !== parent) {
		if (node.hasAttribute('inert')) return true;
		node = node.parentElement;
	}
	return false;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Using closest
const val = img.closest('[inert]');
ready
Using while loop
const val = hasInert(img, div);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.