jQuery get css background-color value of parent element

17,018

Solution 1

Try closest() to find the next matching element up the DOM tree

var color = $(this).closest("div").css("background-color");

Solution 2

$("#voucher_selection_container input:radio").change(function(){

     var color = $(this).parent("div").css("backgroundColor");

});
Share:
17,018
i-CONICA
Author by

i-CONICA

Updated on June 05, 2022

Comments

  • i-CONICA
    i-CONICA almost 2 years

    I want to do something a bit awkward and my pseudo code isn't working, but should explain what I'm trying to do. I have groups of 4 radio buttons, in 6 separate divs, so 24 radios in total. Each div is a particular background colour. When a radio button within a particular div is selected, I need to grab the colour of the div the selected radio button is within, and have it stored in a variable ready to apply it to an element that'll be created next...

        $("#voucher_selection_container input:radio").change(function(){
        //var color = $(this).parent("div").css("background-color");
        //alert(color);
        $("#voucher_customisation_container").slideDown(600);
        //$("#voucher_customisation_container .voucher_box").css("background-color", color);
    });
    

    Any help would be appreciated. :) Thanks.

  • i-CONICA
    i-CONICA about 12 years
    Hi, you're right. Parent would give me a fieldset, I'd need parent().parent(), obviously that's not right, closest works perfectly. Thank you.
  • Toni Michel Caubet
    Toni Michel Caubet about 12 years
    Note that you could have used .parents('div') aswell
  • Andrew Bullock
    Andrew Bullock about 12 years
    @Toni parents('div') will get you all parents that are divs
  • Toni Michel Caubet
    Toni Michel Caubet about 12 years
    I see, but there is a chance that .closest returns a child, isn't it? I would apply a class to the div to make sure. then parents('.class') shouldn't fail
  • izb
    izb about 12 years
    No, closest find the closest UP the DOM tree only, not down.