Add class with jQuery to specific menu-items when hovering

585 Views Asked by At

When hovering a menu with images, I want to add a class with jQuery to the specific menu-item. The menu-items have item-id's which are hardcoded elsewhere. The beneath code is working, but so I have to code every specific menu-item, and that is not my intention.

jQuery(document).ready(function(){
    jQuery('.menu > li.item-447 > a').hover(function() {
        jQuery('.menu > li.item-447 > a > span').toggleClass('nav-label');
    });
    jQuery('.menu > li.item-449 > a').hover(function() {
        jQuery('.menu > li.item-449 > a > span').toggleClass('nav-label');
    });
    jQuery('.menu > li.item-... > a').hover(function() {
        jQuery('.menu > li.item-... > a > span').toggleClass('nav-label');
    });
});

I've tried this code, but on hovering all the menu-items get the extra class 'nav-label'.

jQuery(document).ready(function(){
    jQuery('.menu > li.item > a').hover(function() {
        jQuery('a', this); 
        jQuery( '.menu > li > a > span' ).toggleClass( 'nav-label' );
    });
});

Any suggestions?

1

There are 1 best solutions below

1
On

You can get specific menu-item by this keyword, and use jQuery(this) to transform it to a jQuery object.

Try this:

jQuery(document).ready(function(){
    jQuery('.menu > li > a').hover(function() {
        jQuery(this).children('span').toggleClass('nav-label');
    });
});