Reputation: 23
I have a structure like below
<div data-example="1"></div>
<div data-example="2"></div>
<div data-example="1"></div>
<div data-example="3"></div>
<div data-example="2"></div>
<div data-example="2"></div>
<div data-example="4"></div>
To this structure additional divs can be added with different valued data-example 4-5-6-9 etc.
I want to get indexes of divs with same data-example attr and add it as html element. For example
<div data-example="1">Index is 0 for data 1</div>
<div data-example="2">Index is 0 for data 2</div>
<div data-example="1">Index is 1 for data 1</div>
<div data-example="3">Index is 0 for data 3</div>
<div data-example="2">Index is 1 for data 2</div>
<div data-example="2">Index is 2 for data 2</div>
<div data-example="4">Index is 0 for data 4</div>
For detail
Index is 0 for data 1 this is the first div whch have data-example with 1 value and this is the first div among the div which have data-example value 1 and its index is 0 the second div with data-example = 2 get the index 1.
How can I get the indexes dynamically with jquery.
Upvotes: 2
Views: 42
Reputation: 72299
You have to use jQuery prevAll() like below:-
$('div').each(function(){
var attr = $(this).attr('data-example');
if (typeof attr !== typeof undefined && attr !== false) {
var counter = $(this).prevAll('div[data-example='+$(this).data('example')+']').length;
$(this).text("Index is "+counter+" for data "+$(this).data('example'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-example="1"></div>
<div data-example="2"></div>
<div data-example="1"></div>
<div data-example="3"></div>
<div data-example="2"></div>
<div data-example="2"></div>
<div data-example="4"></div>
<div>Unchanged</div>
Upvotes: 2
Reputation: 4475
You can use the filter function for this.
var allItems = $("div").filter("[data-example]");
var mV = 0;
if (allItems.length > 0) {
$(allItems).each(function(k, v) {
var val = $(this).attr("data-example");
if (mV < val) mV = val;
})
for (var ic = 1; ic <= mV; ic++) {
$(allItems).filter("[data-example='" + ic + "']").each(function(key, value) {
//console.log(key); // this is index
//Here updated the div text correctly.
$($(this)[0]).html("Index is " + key + " data " + ic);
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-example="1">Index is 0 for data 1</div>
<div data-example="2">Index is 0 for data 2</div>
<div data-example="1">Index is 1 for data 1</div>
<div data-example="3">Index is 5 for data 3</div>
<div data-example="2">Index is 1 for data 2</div>
<div data-example="2">Index is 0 for data 2</div>
<div data-example="4">Index is 0 for data 4</div>
Reference: https://stackoverflow.com/a/2903048/7974050
Upvotes: 1