I want to get the index of a group of elements (in this example, the a tags with the class myLink). They are nested within parent elements. All my efforts thus far produce a 0 index for the first item, but a -1 index for the second. An example of the structure I'm looking at is:
// GeekInTheBox - please fill this out
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="containerOne"> <ul class="listOne"> <li> <a class="myLink" href="blah">Link Text</a> </li> <li> <a class="myLink" href="moreBlah">More Link Text</a> </li> </ul> </div> <script> $('.myLink').on('click', function(){ alert($(this).index($('.myLink'))); alert($(this).index($('.containerOne .listOne a'))); alert($(this).index($('.containerOne .listOne li a'))); alert($(this).index($('.containerOne .listOne .myLink'))); alert($(this).index($('.containerOne .listOne li .myLink'))); alert($(this).index($('.containerOne .listOne a.myLink'))); alert($(this).index($('.containerOne .listOne li a.myLink'))); alert($(this).index()); return false; }) </script>
You should call .index()
on a collection of items (such as $('.myLink')
), and pass this
as an argument - then you'll get the index of this
within the collection
// GeekInTheBox - please fill this out
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="containerOne"> <ul class="listOne"> <li> <a class="myLink" href="blah">Link Text</a> </li> <li> <a class="myLink" href="moreBlah">More Link Text</a> </li> </ul> </div> <script> $('.myLink').on('click', function(){ alert($('.myLink').index(this)); return false; }) </script>
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.