jQuery: select first and/or last list items


/ Published in: jQuery
Save to your folder(s)

Select the first and last item in an unordered list. As an example, I add a CSS class to each.

In WordPress, it's not so easy to get wp\_list\_pages() to generate these classes. jQuery provides an easy out for javascript-enabled clients.


Copy this code and paste it in your HTML
  1. <!-- The sort of markup generated by wp_list_pages(), but common elsewhere. -->
  2. <ul class="menu">
  3. <li class="page_item">First Item</li>
  4. <li class="page_item">Second Item</li>
  5. <li class="page_item">Third Item</li>
  6. <li class="page_item">Last Item</li>
  7. </ul>
  8. <script type="text/javascript">
  9. jQuery( document ).ready( function ( $ ) {
  10. // Add first and last menu item classes
  11. $('ul.menu li:first-child').addClass( 'first_item' );
  12. $('ul.menu li:last-child').addClass( 'last_item' );
  13. });
  14. </script>

URL: http://docs.jquery.com/Selectors/firstChild

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.