Reputation: 87
How can I detect the position of a section, which is the first section with a specific class?
For instance I have four sections:
banana
apple
apple
orange
.How can I detect the position of the first occurrence of apple — which would be position 2?
Upvotes: 1
Views: 707
Reputation: 48630
You can write a jQuery plugin to iterate over the elements and retrieve their position.
The following function is a jQuery plugin to iterate over some elements and check if it has a particular class. If it has it, its position will be returned.
(function($) {
$.fn.idiciesOfClass = function(className) {
return this.map(function(index) {
return $(this).hasClass(className) ? index : -1;
}).toArray().filter(function(pos) {
return pos > -1;
});
}
})(jQuery);
(function($) {
$.fn.idiciesOfClass = function(c) {
return this.map((i, e) => $(e).hasClass(c) ? i : -1).toArray().filter(x => x > -1);
}
})(jQuery);
console.log('Apple class indicies:', $('.section').idiciesOfClass('apple').join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section banana">Banana</div>
<div class="section apple">Apple</div>
<div class="section apple">Apple</div>
<div class="section orange">Orange</div>
Apple class indicies: 1, 2
Upvotes: 1
Reputation: 8173
If they are all located within a id='parent'
object, then you can do it like so:
$('#parent').children().each(function (i, v) {
if ($(v).hasClass("apple"))
{
console.log(i);
return false;
}
});
Upvotes: 0
Reputation: 337590
You can use the index()
method to achieve this, if you provide it a selector to group by. Try this:
var appleIndex = $('.apple').index('.section');
console.log(appleIndex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section banana">Banana</div>
<div class="section apple">Apple</div>
<div class="section melon">Melon</div>
<div class="section grape">Grape</div>
Note that the index is zero-based, so the second item would be index 1
, not 2
as in your question. You can easily add 1 to it if require, though.
Upvotes: 4