Muhammad Umer
Muhammad Umer

Reputation: 18097

jquery Index() not working properly?

Take a look: http://jsfiddle.net/dmhsfds4/

basically index gives -1 all the time, even though there is element present with class .current when the function is ran.

Is it a bug?

<p class="current" id="one">Point 1</p>
<p id="two">Point 2</p>
<p id="three">Point 3</p>
<p id="four">Point 4</p>
<p id="five">Point 5</p>
<p id="six">Point 6</p>
<p id="seven">Point 7</p>

var p = $('p');
var i = 0;
setInterval(function(){
    i +=1;
    if (i>6) i=0;

    console.log(p.index('.current'));

    p.removeClass('current').eq(i).addClass('current');
},1000);

Upvotes: 0

Views: 405

Answers (2)

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4453

As mentioned in the jQuery docs,

The function .index() takes an element as a parameter like this.

p.index($('.current'))

and NOT the class or id like this.

p.index('.current') OR p.index('#someId')

Here is the updated fiddle

Upvotes: -1

depperm
depperm

Reputation: 10746

You need to change the p.index() to $('p.current').index(). p.index() is just checking the first p not each one. Here is a fiddle.

Upvotes: 2

Related Questions