I want to get index of selectedclass 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>
Run Code Online (Sandbox Code Playgroud)
I have tried these ways
console.log($('ul li.selected').index());
console.log($('ul li:visible.selected').index());
Run Code Online (Sandbox Code Playgroud)
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"));
Run Code Online (Sandbox Code Playgroud)
Live Example:
var index = $("ul li:visible").index($("ul li.selected"));
Run Code Online (Sandbox Code Playgroud)
console.log($("ul li:visible").index($("ul li.selected")));Run Code Online (Sandbox Code Playgroud)