user726355
user726355

Reputation: 13

how to get the index of a document element with jquery in the following case?

I was wondering how to get the index of span with content itemEleven, with jquery in the following case. Assuming that we aren't able to get element by content value:

    <div>  
        <span class="itemSubMenu">itemOne</span>  
        <span class="itemSubMenu">itemTwo</span>  
        <span class="itemSubMenu">itemThree</span>  
        <span class="itemSubMenu">itemFour</span>  
        <span class="itemSubMenu">itemFive</span>  
        <span class="itemSubMenu">itemSix</span>  
        <span class="itemSubMenu">itemSeven</span>  
    </div>  
    <div>  
        <span class="subMenuitemSubMenu">Something</span>  
        <span class="subMenuitemSubMenu">Something too</span>  
    </div>  
    <div>  
        <span class="itemSubMenu">itemEight</span>  
        <span class="itemSubMenu">itemNine</span>  
        <span class="itemSubMenu">itemTen</span>  
        <span class="itemSubMenu">itemEleven</span>  
        <span class="itemSubMenu">itemTwelve</span>  
        <span class="itemSubMenu">itemThirteen</span>  
        <span class="itemSubMenu">itemFourteen</span>  
        <span class="itemSubMenu">itemFifteen</span>  
    </div>  

When i try to get, for example, itemEight with the following method.

 $(".itemSubmenu").click(function(){
     alert($(this).index());  
 });  

It alerts 0, instead 9. Assuming that it is zero-based-index.

Upvotes: 1

Views: 1115

Answers (4)

Joseph Marikle
Joseph Marikle

Reputation: 78520

Demo

I like this method.

$(".itemSubMenu").click(function(){
    var $this = this;
    var i;
    $(".itemSubMenu").each(function(idx,val){
       if(val === $this) console.log(i = idx);
    })
 });  

Upvotes: 0

Tim Banks
Tim Banks

Reputation: 7179

Have you tried

$(".itemSubMenu").index($(this));

inside of the click event?

Here is a fiddle for you: http://jsfiddle.net/3mDK5/

Upvotes: 3

Adam Terlson
Adam Terlson

Reputation: 12730

Index is always based on its index within its parent.

You'll need to do this:

$(".itemSubMenu").click(function() {
    alert($(this).parent().parent().find('span').index(this));  
});

But really you'd want some sort of contextual selector to base it off of:

$(".itemSubMenu").click(function() {
    alert($('#foo').find('span').index(this));  
});

Fiddle: http://jsfiddle.net/THyAB/

Upvotes: 2

Bobby Borszich
Bobby Borszich

Reputation: 11767

You would need to get the collection of spans with class itemSubMenu and then get the index of this from that collection to get the correct index.

var selected = $(this);
var myIndex = $("itemSubMenu").index(selected);

Upvotes: 0

Related Questions