Reputation: 345
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.
Upvotes: 13
Views: 42026
Reputation: 55740
You can use .find()
$(this).find('> a').addClass("hover_triangle");
This will only access the immediate child elements of nav.menu>ul>li
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')
Upvotes: 2
Reputation: 171679
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] )
Upvotes: 1
Reputation: 3917
$(this).find('a').addClass('hover_triangle')
- more common way bacause it is not necessary to be a direct child
Upvotes: 1
Reputation: 7076
$('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
});
});
Upvotes: 2
Reputation: 7470
$(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');
});
});
Upvotes: 24