简体   繁体   中英

Get index of visible element in jquery

I want to get index of selected class between visible elements in jquery.

<ul>
    <li>element 01</li>
    <li style="display: none">element 02</li>
    <li style="display: none">element 03</li>
    <li style="display: none">element 04</li>
    <li>element 05</li>
    <li>element 06</li>
    <li class="selected">element 07</li>
    <li style="display: none">element 08</li>
</ul>

I have tried these ways

console.log($('ul li.selected').index());
console.log($('ul li:visible.selected').index());

I want the number 3 for the example above: The index of the .selected element in the ul ignoring the elements that aren't visible.

You can use index on the result of selecting the visible elements, passing in the selected element (or a jQuery object containing it). index will find the index of the element within the jQuery set (the visible elements):

var index = $("ul li:visible").index($("ul li.selected"));

Live Example:

 console.log($("ul li:visible").index($("ul li.selected"))); 
 <ul> <li>element 01</li> <li style="display: none">element 02</li> <li style="display: none">element 03</li> <li style="display: none">element 04</li> <li>element 05</li> <li>element 06</li> <li class="selected">element 07</li> <li style="display: none">element 08</li> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

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