I need to find the index of element with class "span":
<div>
<div>
<div class="sd">
<h2> H2 TEXT </h2>
<span> SPAN </span>
<span class="span"> SPAN </span>
</div>
</div>
</div>
So i did:
var q = $('div > div > div.sd').find('.span').index();
alert(q)
This alerts "2" but the class is the first and only so it should alert "1". Is this because Jquery looks for the tag and not the class? I googled a lot and searched on stack but all examples include a click event which I don't want.
Live example: http://jsfiddle.net/jL7dsv5y/
If you apply .index()
to a collection, and pass an element to it, it will return the position of that element within the collection. This will alert 0
because the .span
element within the div
is the first of all the .span
elements in the document.
var q = $(".span").index($('div > div > div.sd').find('.span')); alert(q);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div> <div class="sd"> <h2> H2 TEXT </h2> <span> SPAN </span> <span class="span"> SPAN </span> </div> </div> </div>
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.