How to get the position of a given element in a list through a specific attr?

Asked

Viewed 2,947 times

6

I have a UL with some items. For example

<ul class='ordemQuestoes'>
    <li idquestao="28" >Questao 28</li>
    <li idquestao="2" >Questao 2</li>
    <li idquestao="17" >Questao 17</li>
</ul>

When I save a question I need to record in the bank the order that is among the 3. And this number may vary.

At the time of saving I have in hand the idquestao, then as I do to through the idquestao 17 for example I manage to return 3, third position?

I have not yet been able to think of a logic to achieve this result.

1 answer

10


In the jQuery, index() returns the position of the element within the parent element, counting from zero.

If you already have the <li> as a jQuery object, just ask the index his:

var posicao = liDezessete.index(); // posicao será 2

If you really need to get to the index from the value of the attribute, you can do it with one of the attribute selectors:

var posicao = $('li[idquestao=17]').index();

var posicao = $('li[idquestao=17]').index();
alert(posicao)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='ordemQuestoes'>
    <li idquestao="28" >Questao 28</li>
    <li idquestao="2" >Questao 2</li>
    <li idquestao="17" >Questao 17</li>
</ul>

  • Great, I just had to add + 1 to the result!

Browser other questions tagged

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