简体   繁体   中英

jQuery get index among matched element type

Is there a better way to detect an element's index by type than what I've got? <span> s are interspaced by <em> s. Various tinkering suggests to me I'm still an ignorant programmer.

target.parent('td').children('span').index(target)

HTML Looks like this. I want to get the index 3 for 'time', which the above does. target.index('span') returns 27, so I dunno.

<td>
    <span>once</span>
    <em> </em>
    <span>upon</span>
    <em> </em>
    <span>a</span>
    <em> </em>
    <span>time</span>
    <em> </em>
    <span>in</span>
    <em> </em>
    <span>Mexico</span>
    <em> </em>
</td>

Edit : my previous answer was wrong, as I misunderstood the docs (even though I believe it would be a lot more logical the way I thought it worked), sorry about that!

Updated answer

target.siblings('span').addBack().index(target) should be a tiny bit more efficient, as it won't traverse the DOM back and forth.

It takes the siblings spans + itself and returns its position among it.

Demo:

 $(function() { var target = $('#time'); var position = target.siblings('span').addBack().index(target); console.log(position); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <td> <span>before span 1</span> <span>before span 2</span> <span>before span 3</span> <span>before span 4</span> </td> <td> <span>once</span> <em> </em> <span>upon</span> <em> </em> <span>a</span> <em> </em> <span id="time">time</span> <em> </em> <span>in</span> <em> </em> <span>Mexico</span> <em> </em> </td> </table> 

Previous (incorrect) answer

Just target.index('span') ( docs ) should do it, unless I misunderstood.

Demo:

 $(function() { console.log($('#span1').index('span')); console.log($('#span2').index('span')); console.log($('#span3').index('span')); console.log($('#span4').index('span')); console.log($('#span5').index('span')); console.log($('#span6').index('span')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td> <span id="span1">once</span> <em> </em> <span id="span2">upon</span> <em> </em> <span id="span3">a</span> <em> </em> <span id="span4">time</span> <em> </em> <span id="span5">in</span> <em> </em> <span id="span6">Mexico</span> <em> </em> </td> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM