Help me optimize this jQuery :has selector
I'm using dynaTrace to profile my application in Internet Explorer.
One of the most expensive calls is the following:
$("div.containerClass:has(div.containerHeader)")
I scoped the selector as follows, which offered a little improvement:
$("div.containerClass:has(div.containerHeader)", "#section-wrapper")
How can I improve the performance further?
NOTE: I CANNOT change the HTML markup, only the JavaScript.
I'm using jQuery 1.4.2.
UDPATE Here is sample HTML... note that in my actual application, the HTML is dynamic and the actual markup will vary:
<div id="section-wrapper">
<div class="somethingelse">
<div class="somethingelse2">
<div class="containerClass">
<div class="containerHeader">
<h2>content region 1</h2>
</div>
</div>
<div class="containerClass">
<div>
<h2>content region 2</h2>
</div>
</div>
<div class="containerClass">
<div class="containerHeader">
<h2>content region3 </h2>
开发者_JAVA技巧 </div>
</div>
<div class="containerClass">
<div class="containerHeader">
<h2>content region 4</h2>
</div>
</div>
</div>
</div>
You should use a single selector, like this:
$("#section-wrapper div.containerClass:has(div.containerHeader)")
Otherwise you're firing up multiple jQuery objects just to perform a find. You'll have to test, but depending on the DOM you're working against, this can be much faster (especially in jQuery 1.4.3+):
$("#section-wrapper div.containerHeader").closest("div.containerClass")
While it would be silly if this is indeed faster, have you tried:
$("div.containerClass > div.containerHeader").parents('div.containerClass')
on edit: Added parent selector.
精彩评论