开发者

Targeting First and Last "li" in Each "ul"

开发者 https://www.devze.com 2023-03-30 20:02 出处:网络
I would like to target the first and last \'li\' of a \'ul\' using jQuery and add a class of \"first\" and \"last\" to them accordingly.

I would like to target the first and last 'li' of a 'ul' using jQuery and add a class of "first" and "last" to them accordingly.

I know that using jQuery this is easy if its just a simple 'ul' but I am struggling with the right syntax if the 'ul' has more than one 'ul' nested in the parent 'ul'.

Here is an example of the html markup:

<ul>
    <li><a href="#">Top Level Item</a>
        <ul>
            <li><a href="#">First Sub-Item</a></li>
            <li><a href="#">Last Sub-Item</a>
                <ul>
                    <li><a href="#">First Sub-Sub-Item</a>
                    <li><a href="#">Last Sub-Sub-Item</a></li>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I need to target all of the first and last items of each sub-ul and apply a class to each of them.

Here is what I have been using but it is obviously not working as it is applying the class name to only the very fi开发者_开发百科rst 'li' and the very last 'li'.

jQuery('.topmenu ul li ul li').first().addClass('first');
jQuery('.topmenu ul li ul li').last().addClass('last');

Any suggestions?


I'll assume that everything you have shown is inside something with the class "topmenu". I would advise changing this to an ID if it's unique, and applying a class to the "first ul" so it doesn't have to be avoided algorithmically.

$('.topmenu').find('ul ul li:first-child').addClass('first');
$('.topmenu').find('ul ul li:last-child').addClass('last');

http://jsfiddle.net/aBksB/2/

EDIT: to reflect comment


Here is an example using the code below.

$('ul li ul').find('>li:first').addClass('first').end()
    .find('>li:last').addClass('last');


try using css selector first-child and last-child:

jQuery('.topmenu ul li ul li:first-child').addClass('first');
jQuery('.topmenu ul li ul li:last-child').addClass('last');


Using a > you can specify an imediate child, like this:

$('ul>li').first()

$('ul>li').last()

ul>li gets only the li nodes imediately inside an ul node.


I think you want first-child and last-child:

jQuery('.topmenu ul li ul li:first-child').addClass('first');
jQuery('.topmenu ul li ul li:last-child').addClass('last');


You might try using :first and :last selectors...


  <ul class="myclass">
        <li>Items</li>
        <li>Items</li>
        <li>Items</li>
   </ul>

jQuery(".myclass li:last").addClass("last");

most of the time class to last child not added. The script works perfect if you want to add class to last child of li.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号