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.
To access the index of an element in jQuery, use the eq() method. The eq() method refers the position of the element.
Answer: Use the jQuery :visible and :hidden Selector You can simply use the jQuery :visible or :hidden selector to select all the visible or hidden elements in an HTML page. The jQuery :visible selector considered an element visible if they consume space in the document.
You can use .is(':visible') to check whether an element is visible in the layout or not. Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero. The :visible selector selects every element that is currently visible.
jQuery :eq() Selector The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With