Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery: Set flex of an element based on HTML attribute

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading