Nikola
Nikola

Reputation: 15048

$(this).find("p").text() vs $("p", $(this)).text() in jQuery considering speed

If I have a simple HTML layout like this:

<div class="items">
    <p>Some text #1</p>
</div>
.
.
<div class="items">
    <p>Some text #n</p>
</div>

Which approach of the below two is considered better (if any at all) in terms of speed (if I for the sake of argument have n around 10k) when wanting to iterate over all the divs and then fetching the text of the paragraph:

#1.Approach
$(".items").each(function() {
    var p = $(this).find("p").text();
    //do stuff with p
});

#2.Approach
$(".items").each(function() {
    var p = $("p", $(this)).text();
    //do stuff with p
});

Upvotes: 1

Views: 70

Answers (1)

Tats_innit
Tats_innit

Reputation: 34107

Cool, I reckon you are looking for .find method vs context method

check this (since you are keen)

The context gets translated to the .find so if you want to avoid that use .find

Rest the jspref will show you the performance.

Hope it fits your need. :) although both calls are same.

Upvotes: 2

Related Questions