huMpty duMpty
huMpty duMpty

Reputation: 14460

How to find an element within an element

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');
});

Upvotes: 0

Views: 767

Answers (5)

user1361434
user1361434

Reputation:

You can use jQuery .find() to find elements

Upvotes: 1

Jose Faeti
Jose Faeti

Reputation: 12302

$(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.

Upvotes: 2

Tushar Ahirrao
Tushar Ahirrao

Reputation: 13115

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');
}

Upvotes: 0

Rolando Cruz
Rolando Cruz

Reputation: 2784

$('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

Upvotes: 1

Igor Dymov
Igor Dymov

Reputation: 16460

Try:

var a = $(this).find("a");

Upvotes: 2

Related Questions