Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 9th, 2012  |  syntax: None  |  size: 1.24 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Parent(), faster alternative?
  2. <div id="6179827893" class="dashdiv">
  3.    <div class="buttons">
  4.      <li><a href="#" class="btn1">Button 1</a></li>
  5.      <li><a href="#" class="btn2">Button 2</a></li>
  6.      <li><a href="#" class="btn3">Button 3</a></li>
  7.      <li><a href="#" class="btn4">Button 4</a></li>
  8.      <li><a href="#" class="btn5">Button 5</a></li>
  9.      <li><a href="#" class="btn6">Button 6</a></li>
  10.    </div>
  11.    <div class="dashcontent">
  12.  
  13.     ....
  14.  
  15.    </div>
  16. </div>
  17.        
  18. Method (see below) : Operations per second (higher is better)
  19. parentNode3x       : 4447k
  20. $(parentNode3x)    :  204K
  21. $().closest        :   35k
  22. $().parents        :    9k
  23. $().parent()3x     :   44k
  24.  
  25. // Likely the fastest way, because no overhead of jQuery is involved.
  26. var id = this.parentNode.parentNode.parentNode.id;
  27.  
  28. // Alternative methods to select the 3rd parent:
  29. $(this.parentNode.parentNode.parentNode) // Native DOM, wrapped in jQuery
  30.  
  31. // Slowpokes
  32. $(this).closest('.dashdiv')              // Hmm.
  33. $(this).parents('.dashdiv:first')        // Hmm...
  34.        
  35. var id = this.parentNode.parentNode.parentNode.id;
  36.        
  37. $(this).closest('div.dashdiv').prop('id');
  38.        
  39. $('.dashdiv').click(function(e) {
  40.     if( e.target.nodeName.toLowerCase() === 'a' ) {
  41.         alert( this.id );
  42.     }
  43. });