themonk — 2012-12-20T11:22:35-05:00 — #1
I've been using a piece of jquery code from stack overflow. Here's the link to the page:
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.
chris_upjohn — 2012-12-20T17:26:21-05:00 — #2
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.
- Find the element in the DOM with an ID of #lesson-sidebar
- Within #lesson-sidebar find the top level <ul> element
- Within the top level <ul> element find all the top level <li> elements
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.
themonk — 2012-12-21T10:47:05-05:00 — #3
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.
chris_upjohn — 2012-12-22T17:42:38-05:00 — #4
The documentation is there, its part of the top level jQuery API documents.