Search code examples
jquerycss-selectorschildren

Attaching selectors or child elements to variable name that holds dom element


I saved dom elements to variable names trying to increase performance (not having to traverse the dom everytime).

listGroupsExport = $('#listGroupsExport');

But now I want to call out each LI of that UL. Is there a way to still use the variable name and do the equivalent of $('#listGroupsExport.li') using the var name?


Solution

  • Yes you can use find to find the descendants of your element.

    listGroupsExport.find('li');
    

    if you want to just get the children then:

    listGroupsExport.children('li');
    

    Another way is to use context in the selector:

    $('li', listGroupsExport); //But find will be faster
    

    By the way your selector should anyways be $('#listGroupsExport .li'); //Note the space