Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery, how to find the index of an element amongst its siblings of a specified CSS class

Given the following HTML:

<div class="component">
    <div class="component">
        <div class="component">
        </div>
    </div>
    <div class="component">
        <div class="somethingelse">
        </div>
        <div class="component">
        </div>
        <div class="component">
            <input type="button" value="Get Path" onclick="showPath(this)" />
        </div>
    </div>
</div>

I'm trying to write the function showPath so that it returns the index of the parent div in relation to its siblings of class component. So in the above sample, I would like the function to return 1.

I've got this far, but it returns 2; I don't know what to do to ignore the div of class somethingelse

function showPath(element) {
    var component = $(element).closest('.component');
    alert(component.index());
}
like image 256
sandy Avatar asked Mar 12 '11 00:03

sandy


1 Answers

A quick and simple extension for jQ to turn this process into a method:

$.fn.getIndex = function(){
    var index = $(this).parent().children().index( $(this) );
    return index;
}

Run this on document.ready or wrap it in a function and run it that way (probably cleaner).

Usage is as simple as

var index_for_element = $('.thing-you-want-index-for').getIndex();
like image 131
dclowd9901 Avatar answered Oct 12 '22 12:10

dclowd9901