Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change parent element style with jQuery

I have next html setup:

<div class="one">
    <div class="two">
        <a href="#" class="three">Click</a>
    </div>
</div>

And I want to change background color for element with class .one when I click on element .three with jQuery.

This is what I was trying to use:

$(function(){
    $('.three')(function(){
        $(this).parent().parent().css('backgroundColor', 'red');
    })
});

Here is a fiddle example: https://jsfiddle.net/Munja/a7unbs2p/

I was searching for solution here on SO but wasn't able to find it fast enough (probably I didn't look good enough :/).

Thank you.

like image 266
Dejan Munjiza Avatar asked Dec 25 '15 13:12

Dejan Munjiza


3 Answers

you need to use .click() or .on('click') .. and you can use .closest() as well instead of using parent() twice

$(function(){
    $('.three').on('click',function(){
        $(this).closest('.one').css('backgroundColor', 'red');
    })
});
like image 148
Mohamed-Yousef Avatar answered Sep 30 '22 06:09

Mohamed-Yousef


Just add Click event at your code. First add jquery.min.js then add the script. You can do like this -

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
     $(".three").click(function(){
         $(this).parent().parent().css("background","red");
     });
</script>
like image 26
Sajeeb Ahamed Avatar answered Sep 30 '22 05:09

Sajeeb Ahamed


Since it's a descedant of the element, you can use .parents() which travels up until the selector is found.

Additionally, You can use the CSS syntax inside of the CSS method (background-color instead of backgroundColor).

$('.three').on('click', function(){
    $(this).parents('.one').css('background-color', 'red');
})
like image 22
Donnie D'Amato Avatar answered Sep 30 '22 06:09

Donnie D'Amato