• Find Index of Element with Class Name Using JQuery

    Posted by markzero on Saturday, June 25th, 2011

    Let’s start with an example here. Suppose we have some links (A tags) with classes as days and one will be “today” indicating it as present day (which you may determine by backend PHP or whatever). So, structure would be something like:

    <div class="days-wrapper">
    <a href="..." class="day">M</a>
    <a href="..." class="day">T</a>
    <a href="..." class="day">W</a>
    <a href="..." class="day">T</a>
    <a href="..." class="day">F</a>
    <a href="..." class="day today">S</a>
    <a href="..." class="day">S</a>

    We have Saturday here as today’s day (probably because I’m writing this on Saturday). We need to wrap them somehow, because index needs to know which elements to use (relatively to what element?). In this case it’s days-wrapper DIV.

    First thing first, take today’s element:

    var cur_day = $('.days-wrapper a.today');

    THEN, comes tricky part, which is the reason in most cases index is not working.

    cur_day = cur_day[0];

    Why? Because. The “$” function getting elements by class returns an ARRAY! In this case it’s only one element in array, but it’s still array. Next is default thing:

    var the_day_index = $('.days-wrapper a').index( cur_day );


    Posted in: Javascript, JQuery.

    Share this story:

    Leave a Reply