views:

43

answers:

2

I have a jQuery selector that is running way too slow on my unfortunately large page:

$("#section").find(":visible:input").filter(":first").focus();

Is there a quicker way to select the first visible input without having to find ALL the visible inputs and then filtering THAT selection for the first? I want something like :visible:input:first but that doesn't seem to work.

[Edit] Here's the basic idea of what #section looks like:

<div id="section">
    <div>
        Some text <input type="text">
    </div>
    <div>
        etc. etc. <input type="text">
    </div>
</div>
+2  A: 
$(":input:visible:first", "#section").focus();

If you first filter for the type of control you avoid checking the :visible on all the #section's elements.

It seems like you need only to catch the first input type="text" visible.
This should be a bit faster.

$("input[type='text']:visible:first", "#section").focus();
Alex Bagnolini
This is a different selector, `:input` != `input`
Nick Craver
Fixed, thank you.
Alex Bagnolini
Thanks, this update is about 80ms faster. However this selector is still costing 156ms in IE6. I feel like this should be a quick 16ms lookup or less. Is there any other way to optimizer this?
macca1
I'm accepting the first part of this answer. Seems like the fastest way possible of doing this. Thanks!
macca1
A: 

How about adding class="default_field" to the default field for each page, then using $('.default_field').focus();?

How easy this is to do depends on your server-side technology of course, but the advantages are that it takes the processing burden off of the client (which is extra important for IE6), and it also gives you the flexibility to choose a default input other than the very first one on pages where it's appropriate.

Tobias Cohen