0

I'm trying to change the font color of a a tag in the hover function of the parent li tag.

I'm trying to do something like this

$('li').mouseover(function () {
   var a = $(this).(NEED TO FIND CORRESPONDING a TAG)
    a.css('color', 'white');
});
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
  • Have a look at the documentation: http://api.jquery.com/category/selectors/ – Felix Kling Sep 12 '11 at 09:59
  • possible duplicate of [How to select an element by class inside "this" in Jquery](http://stackoverflow.com/questions/4868599/how-to-select-an-element-by-class-inside-this-in-jquery) – Felix Kling Sep 12 '11 at 10:01

5 Answers5

2
$(this).find('a');

This will find the <a> element inside the <li> element.

Even better:

$('li a').mouseover(function () {
   var a = $(this); // this now refers to <a>
    a.css('color', 'white');
});

Using the selector wisely you can save time by avoiding additional function calls.

Even better, use only a single event listener for the mouse over event, in the parent <ul> tag.

$('ul').mouseover(function (e) {
    var a = $(e.target); // e.target is the element which fired the event
    a.css('color', 'white');
});

This will save resources since you only use a single event listener instead of one for each <li> elements.

Jose Faeti
  • 12,126
  • 5
  • 38
  • 52
2

Try:

var a = $(this).find("a");
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
1

You can use jQuery .find() to find elements

1
$('li').mouseover(function () {
   var a = $("a", this);
   a.css('color', 'white');
});

The second argument specifies the context. So it finds all a in the context of this which is the li

Rolando Cruz
  • 2,834
  • 1
  • 16
  • 24
0

If your parent tag is

<li> and your child tag is <div>

then you can find child tag by using this :

$('li').mouseover(function () {
  var innerElement=$(this).find("div");
  innerElement.css('color', 'white');
}
Tushar Ahirrao
  • 12,669
  • 17
  • 64
  • 96