Ryan King
Ryan King

Reputation: 3696

jQuery List Indexing

I have a series of divs all containing list elements. I'm trying to return the index of the item in the list locally inside the div. But it counts the list items in other divs and I'd like to avoid that.

So currently the indexes it returns are (commas separate the divs):

0-5, 6-7, 8-17

I would like it to return:

0-5, 0-1, 0-9

So I would like the indexing to be relative to each div.

http://jsfiddle.net/K4b8J/1/

JS:

var preview = "<div class=\"preview\"><p>Test.</p></div>";
        $(".category_list.grid > ul li").click(function () {
            // calculate how many elements fit per line
            var index = $(".category_list.grid li").index(this);
            alert(index);
        });

HTML:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<div class="category_list grid">
    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>
<div class="category_list grid">
    <ul>
        <li></li>
        <li></li>
    </ul>
</div>
<div class="category_list grid">
    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>

CSS:

*{padding:0;margin:0}
.preview {clear:both;}
ul {clear:both;}
li {
  width: 5em;
  height: 3em;
  background: black;
    display: inline-block;
    text-align: left;
    margin: 1em;
    color: white;
}
.category_list {margin-bottom:2em; clear:both;}

Upvotes: 0

Views: 100

Answers (1)

Matt Ball
Matt Ball

Reputation: 359966

So you just want to count the element relative to its siblings:

var index = $(this).siblings().andSelf().index(this);

http://jsfiddle.net/mattball/K8Q5D/

and if that's not slick enough:

var index = $(this).prevAll().length;

...because after all, an element's (zero-based) index is simply the number of elements which precede it.

http://jsfiddle.net/mattball/MRPrZ/

Upvotes: 2

Related Questions