jQuery Exclusion Question

I’ve been using a piece of jquery code from stack overflow. Here’s the link to the page:

http://stackoverflow.com/questions/2053190/moving-up-multiple-parents-in-jquery-more-efficient-way/13976196#13976196

I need to hide a large UL tree structure except the root elements. The code above works great except I can’t understand the following line:


$('ul, li', $('#lesson-sidebar ul li')).hide();

That code hides all of teh UL and LI items in the lists, but excludes the root elements. I don’t understand how adding $(‘#lesson-sidebar ul li’) as a selecond selector parameter excludes it from the hide command. I know the hide command doesn’t toggle the visible state so it’s not like they’re hiding the root element and showing it right away. Most other descriptions rely on commands such as :not to exclude the root element.

Can anyone explain why the root elements are not being hidden with that command? (Note that if I remove the $(‘#lesson-sidebar ul li’) part the root elements are in fact hidden.

Thanks :slight_smile:

The second parameter is the selector context which in this case is the top level <ul> > <li> elements, so in English this is what jQuery is doing.

  1. Find the element in the DOM with an ID of #lesson-sidebar
  2. Within #lesson-sidebar find the top level <ul> element
  3. Within the top level <ul> element find all the top level <li> elements

[COLOR=#000000]
Once it has reached the top level <li> element jQuery then runs the first part of the selector which is ‘ul li’ and that now referrers to the child <ul> and <li> elements with the context selection hence why the parent elements don’t get hidden.

Hope that helps bud.[/COLOR]

Thanks for the explanation that makes sense. It’s the first time I’ve seen this type of filter in jQuery. I couldn’t find any documentation on this selector structure. Is there a link to official docs that detail this particular way of selecting elements. I’m curios to see if there are other ways to select/exclude elements like the code above.

Thanks again. :slight_smile:

The documentation is there, its part of the top level jQuery API documents.

http://api.jquery.com/jQuery/