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: /
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.
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/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.
Share Improve this question asked Dec 25, 2015 at 13:23 Dejan MunjizaDejan Munjiza 7981 gold badge12 silver badges23 bronze badges 1- Whoa, thank you @adeneo ! – Dejan Munjiza Commented Dec 25, 2015 at 13:26
5 Answers
Reset to default 7you 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./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');
})
I can't ment, so, little addition to higher answer:
$(function(){
$('.three').on('click',function(){
$(this).closest('.one').css('background-color', 'red');
})
});
Css doesn't have property with name backgroundColor
You can use something like this.
$('.three').on('click',function(){
$(this).closest('.one').css('backgroundColor', 'red');
})