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");
});
Author by
i-CONICA
Updated on June 05, 2022Comments
-
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 about 12 yearsHi, 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 about 12 yearsNote that you could have used .parents('div') aswell
-
Andrew Bullock about 12 years@Toni
parents('div')
will get you all parents that are divs -
Toni Michel Caubet about 12 yearsI 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 about 12 yearsNo, closest find the closest UP the DOM tree only, not down.