I have a multilevel menu like this :
<ul>
<li>item 1
<ul>
<li>item 1.1</li>
<li>item 1.2</li>
</ul>
开发者_如何学JAVA </li>
<li>item 2</li>
<li>item 3
<ul>
<li>item 3.1</li>
<li>item 3.2</li>
</ul>
</li>
<li>item 4</li>
</ul>
In jQuery I have
$("#divId ul li:odd").addClass("blue");
$("#divId ul li:even").addClass("green");
The problem is that jQuery adds the class to all the lists. I would like jQuery to just add the class to the first level (ul > li.class) and NOT the inner childs (ul > li > ul > li.class)
Thanks
This should work:
$("#divId ul:first > li:odd").addClass("blue");
$("#divId ul:first > li:even").addClass("green");
It will add the classes to the children of the first ul tag found in divId.
you could try:
$("#divId ul li:not(#divId ul li ul li):odd").addClass("blue");
$("#divId ul li:not(#divId ul li ul li):even").addClass("green");
I'm going to use assumptions here and you you know what they say about them ;)
If you want to add specific classes to all of the ul items then:
$('ul').addClass('class-addition');
and you can style the list items in the same way.
If you want to add classes to the ul within a li you can use:
$('li > ul').addClass('class-addition');
using the parent > child selectors.
I'd have a look at the selectors documentation provided by Branislav to find exactly what you want and use firebug to test the results though.
Can you, please, give more information on your case. From what I see you need simple select and add class. You can find information on jquery selectors here and on addClass method here
精彩评论