Issue
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?
Solution
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 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>
Or without hardcoding values — by using CSS var():
.container { display: flex; }
.container > * { flex: var(--flex); outline: 1px solid gold; }
<div class="container">
<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 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>
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 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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Answered By - Roko C. Buljan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.