I've got a known container div that I'll be dynamically populating with children. I'd like to specify some .css properties on the children to position them, but I'd like to avoid manually setting the .css styles on each child element that I create. I'll be able to dynamically generate a unique class for each group of elements, so if there is a way to apply css that affects all children of an element that match a certain selector, I'd like to do that.
My application does something like this fiddle.
var numChildren = 0;
$('.myButton').on('click', function(){
$('<div class=childDiv' + numChildren + '>Div!</div>')
.appendTo('.myDiv')
.css({
display: 'inline',
'padding-left': (10 + 10*numChildren) + 'px'
//I'd like to put something like this padding left class on the parent div.
//I know the class of all children that should have this style,
//but I don't know until I create the child.
});
$('<div class=childDiv' + numChildren + '>Div!</div>')
.appendTo('.secondDiv')
.css({
display: 'inline',
'padding-left': (10 + 10*numChildren) + 'px'
});
numChildren++;
});
In this example, I'm dynamically generating several children with a class like childDiv0
. I can manually style them all with a certain padding-left
, but in my actual application, I'm generating lots of elements and the reflow required to quickly render them is slowing down my application. Is there a way to apply the css to the parent instead of to the child? Can I do something similar to this:
$('.parentElement').css(
':childWithSelector(.childDiv'+ numChildren + ').width', //Not a real thing :(
10 + 10*numChildren + 'px'
);
jQuery is optional.