
Untitled
By: a guest on
May 9th, 2012 | syntax:
None | size: 1.24 KB | hits: 14 | expires: Never
Parent(), faster alternative?
<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>
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...
var id = this.parentNode.parentNode.parentNode.id;
$(this).closest('div.dashdiv').prop('id');
$('.dashdiv').click(function(e) {
if( e.target.nodeName.toLowerCase() === 'a' ) {
alert( this.id );
}
});