Reputation: 5531
<li><a href="home.html"> Home </a> </li>
<li> <a href="contact.html">Contact </a></li>
$('li').mouseenter( function() {
$(this).attr('a').css("color", "red");
});
fails. I am trying to understand how to reach that a within that 'li'. (not any 'li a')
Upvotes: 0
Views: 117
Reputation: 144669
a
is an element not an attribute, you can use find
method:
$('li').mouseenter(function() {
$(this).find('a').css("color", "red");
// or using $(selector, context):
// $('a', this).css("color", "red");
});
However JavaScript doesn't work like CSS, you should change the color on mouseleave
event, you can create a class and use toggleClass
method:
.red {
color: red;
}
$('li').hover(function() {
$(this).find('a').toggleClass('red');
});
And you can also use CSS (lighter and faster):
li:hover a {
color: red;
}
Upvotes: 2
Reputation: 74738
You can do this way too:
$('li').mouseenter( function() {
$('a', this).css("color", "red");
});
Upvotes: 0
Reputation: 40639
You can use children
or find
for this
$('li').mouseenter( function() {
$(this).children('a').css("color", "red");
});
Note: Children
only looks at the immediate children of the node, while find
traverses the entire DOM below the node, so children should be faster given equivalent implementations. find uses native browser methods, however, while children uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.
Copied from What is fastest children() or find() in jQuery?
Upvotes: 1