'Set style 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.
How do I fix this?
Solution 1:[1]
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'));
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ryano |
