jQuery add class to certain elements

不问归期 提交于 2019-12-12 14:15:03

问题


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:


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.




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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2011474/jquery-add-class-to-certain-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!