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

Wrap every array of a array group into divs

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 class="row">
    <div class="numbers">2,3,8</div>
  </div>
  <div class="row">
    <div class="numbers">6,7,2</div>
  </div>
</div>

What I need is like this:

<div id="table">
  <div class="row">
    <div class="numbers">
       <div>2</div>
       <div>3</div>
       <div>8</div>
     </div>
  </div>
  <div class="row">
    <div class="numbers">
       <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?

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

>Solution :

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 class="row">
    <div class="numbers">2,3,8</div>
  </div>
  <div class="row">
    <div class="numbers">6,7,2</div>
  </div>
</div>
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