Grork Grork - 11 months ago 46
jQuery Question

Get index of element excluding determinate elements

I've got this HTML structure:

<ul id="list">
<li><i class="icon-remove"></i> file1</li>
<li class="error"><i class="icon-remove"></i> file2</li>
<li><i class="icon-remove"></i> file3</li>

So now, when I click .icon-remove I want to know the index of his parent element (li) excluding (in the count) li.error.

I tried with this:

$("#list li:not(.error) .icon-remove").click(function() {
alert($(this).parent().index($("#list li:not(.error)")));

It returns correct index only for the first element (0). You can check in this jsFiddle

Answer Source


$("#list li:not(.error) .icon-remove").click(function () {
    var $lis = $(this).closest('ul').find('li:not(.error)'),
        $li = $(this).closest('li');