Search code examples
jqueryhoverparent

jquery how to change only one parent closeset <A> tag on hover


I asked similar question here

jquery how to change only one parent on hover

But it's not what I want. so , I re-code and post it again here

I would like to change only one parent on <a> when I hover over <p> tags. The code is:

$('.hover').each(function () {
 $(this).parent().hover(function () {
        $('p').parent(this).css('background-color','red');
    }, function () {
        $('p').parent(this).css('background-color','black');
 });
});

And the HTML is:

<ul>
   <li><a href='#'>1</a> <p class='hover'>A</p></li>
   <li><a href='#'>2</a> <p class='hover'>B</p></li>
   <li><a href='#'>3</a> <p class='hover'>B</p></li>
   <li><a href='#'>4</a> <p class='hover'>X</p></li>
   <li><a href='#'>5</a> <p class='hover'>Y</p></li>
   <li><a href='#'>6</a> <p class='hover'>Z</p></li>
</ul>

What i want is when i hover "A" and "1" is change and other not change and when i hover on "b" and "2" is change other not change also

sorry , im really new in jquery.


Solution

  • there is no need of .each, use .prev

    $('.hover').hover(function () {
            $(this).prev('a').css('background-color','red');
        }, function () {
            $(this).prev('a').css('background-color','yellow');
     });
    

    alternative : you can use .parent().children('a') OR .siblings('a') instead of .prev('a')

    Demo

    Update

    If you want to use .each ( as you mentioned in comment ) then do below.

    $('.hover').each(function () {
     $(this).parent().hover(function () {
            $(this).children('a').css('background-color','red');
        }, function () {
            $(this).children('a').css('background-color','yellow');
     });
    });
    

    Demo using .each