0

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/

7
  • From the documentation: If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements. Commented Dec 14, 2014 at 10:34
  • I'm not sure what you're expecting. It's the first and only of what? Commented Dec 14, 2014 at 10:35
  • Indexes are zero-based, so if you think it's the first, shouldn't it alert 0? Commented Dec 14, 2014 at 10:36
  • @Barmar Its the first and only of element with class "span". Are you saying it can't be done with Jquery index? Commented Dec 14, 2014 at 10:37
  • You can give an argument to index, and it will find its position within that collection. Commented Dec 14, 2014 at 10:37

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, and thank you for elaborating on it:) Im always struggling with index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.