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.
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');
})
});
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>
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');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With