Lower index for multiple elements

0

By default jQuery always returns the highest index when the selector returns more than one element, as in the example below:

<ul>
    <li>1</li>
    <li>2</li>
    <li class="error">3</li>
</ul>
<ul>
    <li class="error">4</li>
    <li>5</li>
    <li>6</li>
</ul>



$('li').click(function(){
    alert($('.error').parents('ul').index());  
})

I also tried this:

alert($('.error')[0].parents('ul').index()); 

However, this statement returns:

  

TypeError: undefined is not a function

    
asked by anonymous 19.02.2015 / 22:49

1 answer

2

Assuming you want to index the item with class error of <ul> current you should use this :

$(this).parent().find('.error').index()

To get the index of the first item with class error relative to <ul> parent:

$('.error:eq(0)').index()

Note that the .index() function with no arguments returns the position of the current item relative to the adjacent elements

Also, if you need the index of the first item with the class error in relation to all <li> use:

$('li').index($('.error'))
    
20.02.2015 / 17:10