3

I have a menu with 2 submenus. I want to target the last li a element in each menu at once and I would like it to be dynamic so if another submenu is added it would find and target its last li a element.

I would like to do with without added any more classes or id's than what is used already. I have tried just targeting the class .sub-menu but it only selects the last sub-menu. Is there a way to select all occurrences?

<ul id="menu-main" class="menu">
 <li class="menu-item-has-children"><a href="#">About</a>
    <ul class="sub-menu">
        <li><a href="#">Our History</a></li>
        <li><a href="#">Strategic Plan</a></li>
        <li><a href="#">Board of Directors</a></li>
    </ul>
</li>
<li class="menu-item-has-children"><a href="#">Programs</a>
    <ul class="sub-menu">
        <li><a href="#">Monthly Calendars</a></li>
        <li><a href="#">Early Years</a></li>
        <li><a href="#">Children and Youth</a></li>
    </ul>
</li>
 </ul>

Right now I am trying

 $('li.menu-item-has-children:nth-child(1) li').last().focusout(function() {
    $(this).parent().parent().removeClass('hover');
    console.log("T removed");
});
$('li.menu-item-has-children:nth-child(2) li').last().focusout(function() {
    $(this).parent().parent().removeClass('hover');
    console.log("T2 removed");
});

Should I make a function that does this for me? I am thinking there must be a easier way.

Thanks, any help is greatly appreciated.

isherwood
  • 58,414
  • 16
  • 114
  • 157
floor
  • 1,519
  • 11
  • 24
  • why are you using nth-child on the first li elements? – Rooster Mar 12 '14 at 19:33
  • The first only targets the last a element on the first submenu. The second does the same only for the second submenu – floor Mar 12 '14 at 19:36
  • 1
    try `$('.sub-menu li:last-child')` – lionel Mar 12 '14 at 19:36
  • @lionel that only targets the last sub menu 's last a element – floor Mar 12 '14 at 19:39
  • @floor actually that targets the last li element inside of sub-menu, if you want to target the a then $('.sub-menu li:last-child a'). This will target both submenus. Or are you asking to target all menu's last li's anchor? as in the main menu + the submenu? For dynamic added elements the answers below with delegation solves that – Huangism Mar 12 '14 at 19:43
  • @floor it targets all submenu's last li element. see [http://jsfiddle.net/8NYQq/](http://jsfiddle.net/8NYQq/). – lionel Mar 12 '14 at 19:46

2 Answers2

1

Use event delegation to handle newly-added sub-menus, and simplify your selector:

$(document).on('focusout', 'ul.sub-menu li:last-child a', function() {
    $(this).parent().parent().removeClass('hover');
    console.log("T removed");
});
isherwood
  • 58,414
  • 16
  • 114
  • 157
1

use like this,because you should use delegation for dynamically added objects.

$(document).on("hover",".sub-menu li:last-child",function(){

});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53