最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change parent element style with jQuery - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 7

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./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');
})
发布评论

评论列表(0)

  1. 暂无评论