add class to child of this
Asked Answered
F

5

13

This code is not working. this+'>a' isn't a valid syntax. So, how can I add/remove a class in a child of this? In this case an a element.

 jQuery(function ($) {
        $("nav.menu>ul>li").hover(
            function () {
               $(this+'>a').addClass("hover_triangle");//error
            },

            function () {
               $(this+'>a').removeClass("hover_triangle");//error
            });
    }); 

I can't do nav.menu>ul>li>a because will select all a elements in menu.

Feverfew answered 29/10, 2012 at 1:25 Comment(0)
A
24
$(this).children('a').addClass('hover_triangle');

and with the full code:

jQuery(function($) {
    $('nav.menu>ul>li').hover(function() {
       $(this).children('a').addClass('hover_triangle');
    },function() {
       $(this).children('a').removeClass('hover_triangle');
    });
}); 
Allier answered 29/10, 2012 at 1:27 Comment(0)
I
2

$('a', this) allows you to look only inside of the this object

jQuery(function ($) {
    $("nav.menu>ul>li").hover(
        function () {
           $('a', this).addClass("hover_triangle");//error
        },

        function () {
           $('a', this).removeClass("hover_triangle");//error
        });
});
Inculcate answered 29/10, 2012 at 1:28 Comment(0)
K
2

You can use .find()

$(this).find('> a').addClass("hover_triangle");

This will only access the immediate child elements of nav.menu>ul>li

CHECK FIDDLE

If you want to just select the immediate children .find('a') will get even the nested anchors.. To avoid that you need to use either .find('> a') or .children('a')

Kapoor answered 29/10, 2012 at 1:30 Comment(0)
M
1

$(this).find('a').addClass('hover_triangle') - more common way bacause it is not necessary to be a direct child

Magda answered 29/10, 2012 at 1:29 Comment(0)
G
1

There are 2 methods to search for descendents of this . Most have replied with find()(and it is easier to read) but a jquery selector also can have a second arfument which is context.

$('a', this) is another syntax and is the same as $(this).find('a) . Internallly jQuery will take the first case and use find() anyway, but the syntax is valid and many use it

API Refrence: jQuery( selector [, context] )

Grubstake answered 29/10, 2012 at 1:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.