views:

71

answers:

2

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> 
            </div> 
            </div> 

            <div class="containerClass"> 
            <div class="containerHeader"> 
              <h2>content region 4</h2> 
            </div> 
        </div> 
    </div>
</div>
+2  A: 

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")
Nick Craver
Am I just confused or can't you just do `$('div.containerClass.containerHeader')`... doesn't the element have both classes?
fudgey
@fudgey - `:has()` means it has a *descendant* with that class :)
Nick Craver
oh duh... LOL *blond moment*
fudgey
Your first example had nearly identical performance to my 2nd example in my question. Your second example did not work for me.... is it functionally equivalent to my example?
frankadelic
@frankadelic - It should be, yes, though your ID is `section-wrapper` and I have this truncated (was just `section-wrapp` in my answer) when I pasted, it's fixed not.
Nick Craver
Your second example didn't work for my HTML, even with the correct id selector.
frankadelic
+1  A: 

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.

jeremy