简体   繁体   中英

Get specific index of element

I have following code:

<div class="something">
  <p class="same"> blah </p> <!-- should return index 0 -->
</div>

<div class="something-else">
  <p class="same"> blah </p> <!-- should return index 1 -->
</div>

<div class="other" >
  <p class="same"> blah </p> <!-- should return index 2 -->
</div>

And my question is simply. How to get index for each paragphs, when the parents are different? I tried something like this:

$('.same').each(function() { console.log( $(this).index() });

but, obviously it returned same value for each element.

$('.same').each(function(index) { console.log( index });

The each function comes with an index parameter.

$(".same").each(function(i) {
   console.log("index " + i); 
});

Full snippet:

 $(".same").each(function(i) { console.log("Item " + i); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="something"> <p class="same"> blah </p> <!-- should return index 0 --> </div> <div class="something-else"> <p class="same"> blah </p> <!-- should return index 1 --> </div> <div class="other" > <p class="same"> blah </p> <!-- should return index 2 --> </div> 

You can use the same class as a selector for .index()

$('.same').each(function() { 
    console.log( $(this).index('.same') );
});

of course, that would return the same index as the each iteration anyway, but that's how you return an index based on a collection using index() , and not just the index of the element based on the parent element

From the docs

.index( selector )

A selector representing a jQuery collection in which to look for an element.

The other way around also works

$('.same').index(this)

You are really close. Inside your function, this holds the context of your current element with the class same. You want to compare it to the whole list of elements with the 'same' class, so

$('.same').each(function() { console.log($('.same').index(this)))

.index() returns the index within its parent. Since each of these paragraphs is the first element in its containing <div> , you just get 0 every time. Instead, you could get the index of the parent:

 $('.same').each(function() { console.log($(this).parent().index()) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="something"> <p class="same">blah</p> <!-- should return index 0 --> </div> <div class="something-else"> <p class="same">blah</p> <!-- should return index 1 --> </div> <div class="other"> <p class="same">blah</p> <!-- should return index 2 --> </div> </div> 

这将起作用:

$('.same').each(function(index) {console.log( index)});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM