Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of visible element in jquery

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>

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.

like image 569
Mahdi Bashirpour Avatar asked Jun 02 '19 09:06

Mahdi Bashirpour


People also ask

How to get the index of an element in jQuery?

To access the index of an element in jQuery, use the eq() method. The eq() method refers the position of the element.

How to get visible element in jQuery?

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.

How to get visible div id in jQuery?

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.

What is EQ jQuery?

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).


Video Answer


1 Answers

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>
like image 159
T.J. Crowder Avatar answered Oct 22 '22 17:10

T.J. Crowder