Lowest index for multiple elements

Asked

Viewed 52 times

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 tried that way too:

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

However, this instruction returns:

Typeerror: Undefined is not a Function

  • What you want to return?

  • The lowest index value

  • Tried $('. error'). Closest('ul'). index(); ? But from what I saw, what you get is index(), are das li, in your case it would be $(this). index()...

  • or $('.error'). Closest('ul'). find('li:first'). index(); NOTE: I have not tested

  • 1

    I don’t know if that’s what you want, but try: $('.error').eq(0).parent().index()

  • Have you solved the problem? I still don’t understand what you want.

Show 1 more comment

1 answer

2

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

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

To get the index of the first item with the class error in relation to <ul> father:

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

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

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

$('li').index($('.error'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.