John Harrison John Harrison - 11 months ago 46
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


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


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


$('#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());


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 {
      label: $fields.eq(0).text().trim(),
      description: $fields.eq(1).text().trim()