How can I wrap all array values per row, not as summery of all? My code gives me all arrays in every row.
var numbers = $("#table > .row > .numbers").text().split(','); // to get them as array
$.each(numbers, function(index, value) { // wrap every array number in a div
$('#table > .row').append("<div>" value "</div>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div id="table">
<div >
<div >2,3,8</div>
</div>
<div >
<div >6,7,2</div>
</div>
</div>
What I need is like this:
<div id="table">
<div >
<div >
<div>2</div>
<div>3</div>
<div>8</div>
</div>
</div>
<div >
<div >
<div>2</div>
<div>3</div>
<div>8</div>
</div>
</div>
</div>
How to wrap every array of a array group inside .row
, not all together of the whole #table
?
CodePudding user response:
The issue with your logic is that you're selecting all .numbers
elements and creating one array with every value. Then as you iterate through the array, you append all the values in each .numbers
element, not just the ones relevant to that specific element.
To do what you require you can provide a function to jQuery's html()
method which accepts the HTML of the current element as an argument.
You can then split()
this in to an array of values and map()
it to create an array containing HTML strings with the values wrapped in div
elements. If you return this to html()
it will then append that content within the current .numbers
element as it iterates through them all:
$('.numbers').html((i, html) => html.split(',').map(i => `<div>${i}</div>`));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div id="table">
<div >
<div >2,3,8</div>
</div>
<div >
<div >6,7,2</div>
</div>
</div>