jquery index() with some specific selector...?

html-lists, indexing, javascript, jquery, jquery-selectors

Solution

With the following markup:

<ul>
  <li>Foo</li>
  <li>Bar</li>
  <li style="display:none">Fiz</li>
  <li>Buz</li>
</ul>

We can determine the (zero-based) index of the last `li` all visible list items:

// 2
$("li:last").index("li:visible");

If we were to remove the `:visible` selector, and ask for the index of the last among all:

// 3
$("li:last").index("li");

Update: Using a Variable

If you had a variable reference to a specific list item:

var lastItem = $("#parent li:last");

You could still get its index among visible children in the same container:

var index = $(lastItem).index("#parent li:visible");

Update 2: No Explicit Parent ID

var index = lastItem.parent().find("li").index( lastItem );

Problem

I have a parent with li's, and given the pointer to a li, I want to get it's position as a child. For this I used: ``` li.index() ``` Now... I have one more condition, it should find an index only among these children that have display:block property in css. I tried it some other ways around but I was unable to solve it. Do have any ideas? Edit: PS: or, rather for these that do not have display:none property. EDIT 2: Well I these all require the reference to parent or specific ids, but what if have only a pointer to a li, for example: ``` <ul> <li>Foo</li> <li>Bar</li> <li>Fiz</li> <li>Buz</li> </ul> li=$('li:nth-child(n)'); ``` now, let's suppose I know only one variable, and I want it's index among these that don't have css display: none propery... Solved This is what did it: ``` li.add(li.siblings()).filter(':visible').index( li ); ``` Thanks for helping me out with great ideas and different approach. :)

Original source