Emmet B
Emmet B

Reputation: 5531

Jquery: Accessing a tag element inside $(this)

<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

Answers (4)

Ram
Ram

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

Jai
Jai

Reputation: 74738

You can do this way too:

$('li').mouseenter( function() { 
   $('a', this).css("color", "red");   
});

Upvotes: 0

Rohan Kumar
Rohan Kumar

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

Adil
Adil

Reputation: 148110

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

$('li').mouseenter( function() { 
    $(this).find('a').css("color", "red");   
});

Upvotes: 1

Related Questions