Carry the first level <li> s, not the nested <li> s

I have the following HTML:

<ul> <li>A <ul> <li>subsection</li> </ul> </li> <li>B <ul> <li>subsection</li> </ul> </li> <li>C <ul> <li>subsection</li> </ul> </li> </ul> 

With jQuery, how to target the FIRST level <li> s?

For example, I need to make the font bold when hovering over the <li> with the letters A, B, and C, but DO NOT use this font style for nested <li> (with subsections of names).

Here you can use the initial jsfiddle DEMO if you want to use it.

Thank.

EDIT -

Decision:

CHILD SELECTORS that answer.

No jQuery needed, this can be done using CSS.

Here is the updated DEMO

EDIT - Here's a clearer demonstration.

Thank,

+45
jquery css html-lists
Jan 28 '11 at 16:30
source share
5 answers

You have a <div> container with a class and use the selector > . Lets say your container div class is "myclass":

 .myclass ul li { ...this will affect both levels of li. } .myclass > ul > li { ...this will only affect the first level. } .myclass > ul > li > ul > li { ...this will only affect the second level. } 

Note. The > selector does not work in IE6 and below when used as a CSS selector. It works in all other browsers, including IE7 and IE8, and when used in jQuery, it works in all browsers supported by jQuery, including IE6.

+81
Jan 28 2018-11-11T00:
source share

You can do it:

 $('ul > li:not(:has(ul))'); 

But it would be better to assign your top-level identifier <ul> so that you can customize it with a valid CSS selector:

 $('#topUL > li') 
+16
Jan 28 '11 at 16:32
source share

CHILD SELECTORS that answer.

No jQuery needed, this can be done using CSS. Customize the first level li elements using the selector:

 ul > li { font-weight: bold; } 

And then undo the style for deeper li elements:

 ul > li li { font-weight: normal; } 

Here updated DEMO .

+8
Jan 28 2018-11-11T00:
source share

I would set one rule to target all li elements and then another to override this, which is for nested li elements.

 li{font-weight:bold;} ul ul li{font-weight:normal;} 

Nested li elements will have normal weight, and the upper level will be bold.

+1
Jan 28 2018-11-11T00:
source share

I do not think your problem has been completely resolved (although there have been some good attempts). Your sample problem is applying the style to the parent and preventing the child from inheriting the style, which is a CSS issue.

You can target list items by knowing the parent item (as some have noted). Then add the class on hover.

 $('div > ul > li').hover(function(){ $(this).addClass('myHover'); }, function(){ $(this).removeClass('myHover'); }); 

And your CSS will have a class for the parent and a negation style for the children:

 .myHover { font-weight: bold; } .myHover li { font-weight: normal; } 
+1
Jan 28 '11 at 16:48
source share



All Articles