Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to loop through elements with data attribute

I have several divs that looks like this:

<div class='popupDiv' data-layergroup='layer1'>divcontent 1</div>
<div class='popupDiv' data-layergroup='layer1'>divcontent 2</div>
<div class='popupDiv' data-layergroup='layer2'>divcontent 3</div>
<div class='popupDiv' data-layergroup='layer2'>divcontent 4</div>

I'm a bit stumped as to how to loop through all popupDiv divs, and then loop through each layergroup separately. I want to end with a single array for each layergroup. I'd need something like:

var mainArray = [];
$('.popupDiv').each(function(){
    var tempArray = [];
    $([unique layer value]).each(function(){
        // Put div values from layergroup in tempArray
    });
    mainArray.push(tempArray);
});
return mainArray;

But I don't know the syntax I'm looking for. What do I do?

like image 734
yesman Avatar asked Oct 09 '14 06:10

yesman


2 Answers

<div class='popupDiv' data-layer='layer1'></div>
<div class='popupDiv' data-layer='layer1'></div>
<div class='popupDiv' data-layer='layer2'></div>
<div class='popupDiv' data-layer='layer2'></div>

Loop through the elements

$('.popupDiv[data-layer]').each(function(){

});

to loop through each group seperately, you can use below logic

 //create an array to store processed data-layer type
 var dataArray = new Array();
    $('.popupDiv').each(function(){
      var dataLayer = $(this).data('layer');
      //check if data-layer already processed
      if(!dataArray.indexOf(dataLayer))
      {
         //update data array
         dataArray.push(dataLayer);
         $('.popupDiv[data-layer="'+ dataLayer +'"]').each(function(){
            //do your stuff here
         });
      }
    });
like image 176
Bhushan Kawadkar Avatar answered Sep 23 '22 17:09

Bhushan Kawadkar


You do not need two each loops here. You can use Has Attribute Selector. you are also having duplicate IDs for divs. IDs should be unique, use class name instead:

$('[data-layergroup]').each(function(){
    // Do stuff with each div
    console.log($(this).data('layergroup'));//current data layer value
});

For iterating over the values(FYI-BAD APPROACH):

$.each($("[data-layergroup]").map(function() {  return $(this).data('layergroup');}).get(), function(index, item) {
   // item
});
like image 33
Milind Anantwar Avatar answered Sep 24 '22 17:09

Milind Anantwar