Jquery how to change only one parent on hover

I want to change only one parent when I hang over tags <p>. The code:

$('.hover').each(function () {
    $(this).parent().hover(function () {
            $('p').parent(this).css('font-size','30px');
        }, function () {
            $('p').parent(this).css('font-size','10px');
    });
});

and HTML:

   <ul>
        <li>1 <p class='hover'>xxxx</p></li>
        <li>2 <p class='hover'>yyyy</p></li>
    </ul>

When I am above "xxxx" I want to change "1" and "xxxx", but "2" and "yyyy" do nothing, and when I hang "yyyy" I want to "2" and "yyyy" "change but "1" and "xxxx" do nothing.

I am new to jQuery.

+5
source share
3 answers
$('p.hover').parent().hover(function() {
    $(this).children('p').css('font-size','30px');
}, function () {
    $(this).children('p').css('font-size','10px');
});

You do not need to use each loop to add freezes. If you select multiple items, it will apply the event to all items.

Having said that, I optimized your code a bit.

, . $(this) , .

, , .


:

  • ($('p.hover'))
  • li (.parent())
  • (.hover())

:

  • ($(this))
  • (.children('p'))
+6

$('p').closest('li').css('font-size','30px');
0

Parent <p>in your case <li>. You need:

$('.hover').parent().parent().hover(
    function () {
        $(this).css('font-size','30px');
    }, function () {
        $(this).css('font-size','10px');
    });
0
source

All Articles