Q:

ilterate through html elements with specific id with jQuery

I have the following piece of phtml code:
<div id='calendar'>
<?php foreach($eventCollection as $event) { ?>
    <div id="<?php echo $event['id']?>">
        <div class="title" data-mage-init="<?php echo $event['title']?>"></div>
        <div class="start" data-mage-init="<?php echo $event['start']?>"></div>
        <div class="end" data-mage-init="<?php echo $event['end']?>"></div>
    </div>
<?php } ?>

$event['id'] is a series of incrementing integer from 0. Now I want to write some jQuery code that find the element of id calendar, then iterate through div elements with the integer id and get the value of data-mage-init and put them in an array. Is that doable?

A:

You can do it like below. You can iterate through 1 level nested DIV inside #calendar and then again loop through each individual div inside that and build your array.
HTML
<div id='calendar'>
    <div id="0">
        <div class="title" data-mage-init="first"></div>
        <div class="start" data-mage-init="first start"></div>
        <div class="end" data-mage-init="first end"></div>
    </div>
     <div id="1">
        <div class="title" data-mage-init="second"></div>
        <div class="start" data-mage-init="second start"></div>
        <div class="end" data-mage-init="second end"></div>
    </div>
    <div id="2">
        <div class="title" data-mage-init="third"></div>
        <div class="start" data-mage-init="third start"></div>
        <div class="end" data-mage-init="third end"></div>
    </div>
</div>

JS
$(function() {
    var result = [];
    $( "#calendar > div" ).each(function() {
      var myObj = {};
        var $el = $(this);
      myObj['id'] = $el.attr('id');
      myObj['data'] = [];
      $el.find('div').each(function() {
          myObj['data'].push($(this).attr('data-mage-init'));
      });
      result.push(myObj);
    });
    console.log(result);
});

NOTE: Result will be something like: [Object { id="0",  data=[3]}, Object { id="1",  data=[3]}, Object { id="2",  data=[3]}]

