Grork Grork - 1 year ago 80
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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download