Parent(), faster alternative?

jQuerybeast picture jQuerybeast · Jan 9, 2012 · Viewed 7.5k times · Source

I am working with a dashboard of divs and each div it has a tree of which the buttons are. Every time I have to know which the id of that div is so I am using parent() alot.

Mostly I am doing $(this).parent().parent().parent() to find the ID of div so I can set variables to it. The app is based on the id's of each div.

Is it consider slow to use parent() up to 3 times but pretty much on every function?

Is there any other alternative?

I am looking for something like benchmarks-style which shows what's faster.

Here is an example of the tree:

<div id="6179827893" class="dashdiv">
   <div class="buttons">
     <li><a href="#" class="btn1">Button 1</a></li>
     <li><a href="#" class="btn2">Button 2</a></li>
     <li><a href="#" class="btn3">Button 3</a></li>
     <li><a href="#" class="btn4">Button 4</a></li>
     <li><a href="#" class="btn5">Button 5</a></li>
     <li><a href="#" class="btn6">Button 6</a></li>
   </div>
   <div class="dashcontent">

    ....

   </div>
</div>

Answer

Rob W picture Rob W · Jan 9, 2012

You've got a few options to achieve the same effect.

Benchmark: http://jsperf.com/parents-method. According to this benchmark, my method is roughly 100x faster than your method.

Method (see below) : Operations per second (higher is better)
parentNode3x       : 4447k
$(parentNode3x)    :  204K
$().closest        :   35k
$().parents        :    9k
$().parent()3x     :   44k

// Likely the fastest way, because no overhead of jQuery is involved.
var id = this.parentNode.parentNode.parentNode.id;

// Alternative methods to select the 3rd parent:
$(this.parentNode.parentNode.parentNode) // Native DOM, wrapped in jQuery

// Slowpokes
$(this).closest('.dashdiv')              // Hmm.
$(this).parents('.dashdiv:first')        // Hmm...