Dupuis David
Dupuis David

Reputation: 421

jQuery index() does not return the correct position

I want to know the index of an element with a specifical id on a list. I write an example of what I want on this fiddle: https://jsfiddle.net/c4n0q53e/ I just used what the jQuery documentation said...

var index = $("li").index("#is-selected")
$(".result").html(index);

Do someone see what's is the problem on this simple code ?

Upvotes: 2

Views: 66

Answers (3)

webbul
webbul

Reputation: 162

Here you go: fiddle

var var1 = $("#is-selected").index();
$(".result").append(var1);

Upvotes: 0

Cornwell
Cornwell

Reputation: 3410

The parameter for index is an element not the selector. This works:

var index = $("li").index($("#is-selected"))

Upvotes: 0

John Boker
John Boker

Reputation: 83699

shouldnt it be more like this?

https://jsfiddle.net/7vwg7g97/1/

var index = $("#is-selected").index("li")
$(".result").html(index);

this looks for #is-selected within the results of the selector li

Upvotes: 2

Related Questions