jQuery closest() faster than parents()

Benchmark created by acusti on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<section id="introduction">
<article class="multiple">
<h1>A title</h1>
<p>An <b>article</b></p>
</article>
<article class="multiple">
<h1>A title</h1>
<p>An <b>article</b></p>
</article>
<article class="multiple">
<h1>A title</h1>
<p>An <b>article</b></p>
</article>
</section>
<section id="conclusion">
<article class="single">
<h1>A title</h1>
<p>An <b>article</b></p>
</article>
</section>

Test runner

Ready to run.

Testing in
TestOps/sec
Traversing up the tree with parents()
$('b').each(function() {
  var $article = $(this).parents('article');
  if ($article.hasClass('multiple')) {
    if (window.console) console.log('Article is one of many');
  } else if ($article.hasClass('single')) {
    if (window.console) console.log('Article is the only one');
  }
});
ready
Traversing up the tree with closest()
$('b').each(function() {
  var $article = $(this).closest('article');
  if ($article.hasClass('multiple')) {
    if (window.console) console.log('Article is one of many');
  } else if ($article.hasClass('single')) {
    if (window.console) console.log('Article is the only one');
  }
});
ready

Revisions

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