I have a div with several child divs like this:
<div class=container>
<div data-value="3">div 1</div>
<div data-value="2">div 2</div>
<div data-value="1">div 3</div>
<div data-value="2">div 4</div>
</div>
I need to set the flex
attribute of each to its data-value
. I came up with this:
$('.container > div').css('flex', $(this).attr('data-value'));
but that doesn't work - probably because that's not how $(this)
is used.
How do I fix this?
CodePudding user response:
You don't need JS.
.container { display: flex; }
.container > * { outline: 1px solid gold; }
[data-value] { flex: 1; } /* default to 1 */
[data-value="2"] { flex: 2; }
[data-value="3"] { flex: 3; }
<div >
<div data-value="3">div 1</div>
<div data-value="2">div 2</div>
<div data-value="1">div 3</div>
<div data-value="2">div 4</div>
</div>
Or without hardcoding values — by using CSS var():
.container { display: flex; }
.container > * { flex: var(--flex); outline: 1px solid gold; }
<div >
<div style="--flex:3">div 1</div>
<div style="--flex:2">div 2</div>
<div style="--flex:1">div 3</div>
<div style="--flex:2">div 4</div>
</div>
If you totally need JavaScript - than you don't need jQuery
document.querySelectorAll("[data-value]").forEach(el => el.style.flex = el.dataset.value);
.container { display: flex; }
[data-value] { outline: 1px solid gold; }
<div >
<div data-value="3">div 1</div>
<div data-value="2">div 2</div>
<div data-value="1">div 3</div>
<div data-value="2">div 4</div>
</div>
If you totally need jQuery (— which you don't, in 2022):
$("[data-value]").css("flex", function () {
return $(this).attr("data-value");
});
.container { display: flex; }
[data-value] { outline: 1px solid gold; }
<div >
<div data-value="3">div 1</div>
<div data-value="2">div 2</div>
<div data-value="1">div 3</div>
<div data-value="2">div 4</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
CodePudding user response:
First put "" around the "container" attribute value in the parent div.
I think you'll need to use a .each() to loop over all the elements you want, then $(this) will refer to each element in turn.
So something like this...
$('.container > div').each(function() {
$(this).css('flex', $(this).attr('data-value'));
});