ahren
ahren

Reputation: 16959

Get position of selected elements, not index of element in DOM

<div>
  <h3>Heading one</h3>
  <h3>Heading two</h3>
  <h4>heading caption</h4>
  <h3>Heading three</h3>
</div>​

I want to get the position of the element within the jQuery selection, rather than it's index in the DOM.

At the moment, if I alert($("h3").eq(2).index()); I'll get '3' - I want '2'.

http://jsfiddle.net/4QmEF/

Upvotes: 4

Views: 520

Answers (2)

Sumit Thakur
Sumit Thakur

Reputation: 71

<div>
   <h3>Heading one</h3>
   <h3>Heading two</h3>
   <h4>heading caption</h4>
   <h3>Heading three</h3>
</div>

<script type="text/javascript">
$(document).ready(function(){ 
    $("div").children().each(function(){  
        $(this).click(function(){
            alert($(this).context.innerHTML);
        });  
    });
});
</script>`

Upvotes: 0

Mike Robinson
Mike Robinson

Reputation: 25159

Pass your index() a selector:

alert($("h3").eq(2).index("h3"));

Upvotes: 7

Related Questions