0
<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')

UiUx
  • 967
  • 2
  • 14
  • 25
Emmet B
  • 5,341
  • 6
  • 34
  • 47

4 Answers4

2

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;
}
Ram
  • 143,282
  • 16
  • 168
  • 197
1

Use find() instead of attr() as a is element not the attribute of current element.

$('li').mouseenter( function() { 
    $(this).find('a').css("color", "red");   
});
Adil
  • 146,340
  • 25
  • 209
  • 204
1

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?

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

You can do this way too:

$('li').mouseenter( function() { 
   $('a', this).css("color", "red");   
});
Jai
  • 74,255
  • 12
  • 74
  • 103