3

I have a multilevel menu like this :

<ul>
  <li>item 1
    <ul>
      <li>item 1.1</li>
      <li>item 1.2</li>
    </ul>
  </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

1
  • 6
    You have a multilevel menu like THAT? Do go on! Maybe with a question? Commented Jan 6, 2010 at 7:29

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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");

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.