jQuery optimised chaining

Hi I have just written some jQuery code that had to navigate to a parent sibling then 3rd child

my code was

$(this).parent().next(‘ul’).children(‘li’).children(‘span’).children(‘input’).attr(‘checked’, ‘checked’);

I was wondering if there is any way to optimise this I thought this would work

$(this).parent().next(‘ul’).children(‘li span input’).attr(‘checked’, ‘checked’);

It depends if you have any other inputs in your list besides those you are checking. For example you could like this if you want to check any input element in the list:


$(this).parent().next('ul').find('input').attr('checked', 'checked');

If you can post your piece of code related to this query, it will be easier to suggest something more.

It is a unordered list of checkboxes and then sub lists of checkboxes too. There could be x number of list items in the top level list or sub lists but only one level of depth.

It is structured like this:

<li>
    <span>
        <a href="javascript://">Expand / Collapse</a>
        <input type="checkbox" name="checkBoxMarital" id="checkBoxMarital" />
        <label for="checkBoxMarital">Marital Status</label>
    </span>
    <ul>
        <li>
            <span>
                <input type="checkbox" name="checkBoxMaritalSingle" id="checkBoxMaritalSingle" />
                <label for="checkBoxMaritalSingle">Single</label>
            </span>                                                            
        </li>

If you need to make sure that the input is in the list and then span the most efficient way would be…

$(this).parent().find('ul > li > span > input').attr('checked', 'checked');

Is there any reason why you can’t just do the following though?

$(this).parent().find('ul input').attr('checked', 'checked');

Yeah, it should work with anything, it’s equivalent to the > CSS selector in that it looks for the direct child of the tag.

Thanks,

Thats a pretty nice short cut, I have not used find before.

Does the > operator work in other tags like

.parent('ul > li')

The most optimized way to get input elements in your example would be


$(this).parent().next().find('input').attr('checked', 'checked');

If you need some restrictions like ‘input’ should be inside of ‘span’, just add only those that really required, because each additional restriction will add time to function execution.