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?
<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
});
}
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With