Reputation: 141
I'm looking to apply css not only to the closest 'div', but to all child elements of the div.
The code i have at the moment looks like this
$(document).ready(function(){
$(".classname").closest('div').css({"background-color": "purple"});
});
This only puts a background on the div, which contains eight white select boxes, i'd like them all to have the same background color.
With regular css i'd do this by .classname > *{background-color:red;}
The html is similar to
<div>
<select>
<option class="classname"></option>
</select>
<select>
<option class="other"></option>
</select>
<select>
<option class="other"></option>
</select>
<select>
<option class="other"></option>
</select>
</div>
Upvotes: 0
Views: 2850
Reputation: 21
Your CSS example applies the background to all the direct children of .classname. To achieve the same result using jQuery you can do the following:
$(document).ready(function(){
$(".classname").children().css({"background-color": "purple"});
});
The 'closest' function in jQuery looks for the closest ancestor of the selected element that matches the selector, starting from the element itself. In your code, .classname seems to be a div, so .closest('div') matches the element itself (having no effect) and the background is applied to it.
Upvotes: 1
Reputation: 119
You can use jquery .children
$(".classname").closest('div').css({"background-color": "purple"});
$(".classname").closest('div').children().css({"background-color": "purple"});
Upvotes: 1
Reputation: 1951
you can use the following code below
$(document).ready(function(){
var purpleBackgroundCss = {"background-color": "purple"};
$(".classname").closest('div').css(purpleBackgroundCss).children('div').css(purpleBackgroundCss);
});
Upvotes: 0