<div id='curBody1'>
<div>
<span>
<div>
This is a div we're NOT looking for.
</div>
</span>
</div>
</div>
<div id='curBody2'>
<div>
<span>
<div class='desired-element'>
This is the div we're looking for.
</div>
</span>
</div>
</div>
var curElement = null;
var parentEl = $("#curBody2"); //Used for last two test cases only.
curElement = $('#curBody2 .desired-element');
curElement = $('.desired-element');
curElement = $('#curBody2').find('.desired-element');
curElement = $('.desired-element',$('#curBody2'));
curElement = parentEl.find('.desired-element');
curElement = $('.desired-element',parentEl);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Id and class chaining selector | |
Class selector only | |
Id selector then .find | |
Class selector using parent element | |
parentEl with .find | |
Class selector using parentEl |
Test name | Executions per second |
---|---|
Id and class chaining selector | 323155.2 Ops/sec |
Class selector only | 570200.0 Ops/sec |
Id selector then .find | 439855.9 Ops/sec |
Class selector using parent element | 395986.1 Ops/sec |
parentEl with .find | 791879.7 Ops/sec |
Class selector using parentEl | 551895.9 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark.
What is being tested?
The benchmark measures the performance difference between three ways to select an element using jQuery:
$('.desired-element')
$('#curBody2 .desired-element')
.find
: $('#curBody2').find('.desired-element')
Options compared
The benchmark compares the performance of these three methods, which involve different levels of DOM traversal:
.find
: first finds an element by its ID, then uses the .find()
method to search for the desired child element.Pros and Cons of each approach
.find
:.find()
method to search for the desired element.Other considerations
parentEl
), which affects the performance of the .find()
method.Alternative approaches
Other ways to select elements using jQuery include:
$('#curBody2 .desired-element')
with a different selector (e.g., .class-selector
)$('*').filter()
, which can be slower and less efficient than direct class selectors or IDs.$(document).ready()
or $('body').find()
Keep in mind that the best approach will depend on the specific use case and requirements of your project.