Wednesday, April 13, 2011

Help me optimize this selector? $('#data div.item:has(div.video_guid:empty)')

It's currently not so slow as to make the site unusable, but in mobile safari on the iphone there is a noticeable lag. Is there a simpler way to do this?

"Find div.items that have an empty div.video_guid"

From stackoverflow
  • Are there div's with a class video_guid anywhere else on the page? If not, you could simplify it to:

    $('div.video_guid:empty');
    

    The only difference between your selector and mine is that yours would match the parent div.item while mine would match the actual div.video_guid. To get around this, once my selector matches, if you want to perform operations to the parent div.item you could just do:

    $('div.video_guid:empty').each(function() {
        var container = $(this).parents('div.item');
        // do something to the containing div
    });
    

    All things considered, I would expect that to perform better..

    jackb : Yes these are the only div.video_guid:empty on the page. I was under the impression though that specifying the container in the selector aided performance, ie: $('#thecontainer div.video_guid:empty'); OR $('div.video_guid:empty','#thecontainer'); I'll see if I can run some tests, thanks!
    Paolo Bergantino : That is actually correct. I'd probably change mine to have a second argument of #data
  • Read this related question. According to this,

    $(‘div.item:has(div.video_guid:empty)’, '#data')
    

    should be faster. Strange, but apparently measurable.

0 comments:

Post a Comment