How do I get the position of a certain element in a list through a specific attr?

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 an issue, I need to save the order in the bank that is between 3. And that number may vary.

At the time of saving I have the idquestao in hand, so how do I go through idquestao 17 for example I can get 3, third position?

I could not think of a logic to achieve this result.

    
asked by anonymous 28.11.2014 / 19:19

1 answer

10

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

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

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

If you really need to get into the index from the value of the attribute, you can do 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><ulclass='ordemQuestoes'><liidquestao="28" >Questao 28</li>
    <li idquestao="2" >Questao 2</li>
    <li idquestao="17" >Questao 17</li>
</ul>
    
28.11.2014 / 19:27