John Harrison John Harrison - 3 months ago 10
Javascript Question

Looping through div rows and collecting the id of the row and column values

I have divs acting like a table and I want to loop through each div row in jquery and collect the column values (and also the row id)

How can I do it? code is in this jsffiddle

https://jsfiddle.net/DTcHh/24064/

HTML

<div id="tasksTableDiv">
<div class="row taskRow" id="1">
<div id="description_1"
class="col-sm-2 taskDescriptionCol">Description 1
</div>
<div id="colour_1"
class="col-sm-2 taskColourCol">Blue
</div>
</div>
<div class="row taskRow" id="2">
<div id="description_2"
class="col-sm-2 taskDescriptionCol">Description 2
</div>
<div id="colour_1"
class="col-sm-2 taskColourCol">Red
</div>
</div>

</div>

<button id="loopButton" type="button"
class="btn btn-sm btn-primary">Loop</button>


JS

$('#loopButton').on('click',function() {
var ids = [];
var row = $('.taskRow');
$.each( row, function() {
// get the id of each row and get the description and colour
// ids.push( push the id you got);
console.log("in loop" + row.html());
});
});

Answer

You can use jQuery's .map() to loop over the elements and create an array of extracted properties (demo):

$('#loopButton').on('click', function() {
  var ids = [];
  var rowsData = $('.taskRow').map(function(index, element) {
    var $fields = $(this).find('div');
    return {
      id: this.id,
      label: $fields.eq(0).text().trim(),
      description: $fields.eq(1).text().trim()
    };
  }).toArray();

  console.log(rowsData);
});
Comments