Home > Enterprise >  jQuery get index of nested element in relation to other nested elements with same class
jQuery get index of nested element in relation to other nested elements with same class

Time:03-09

First of all, sorry if the title isn't accurate, I can't think of a better title.

I have a similar structure like this:

<ol>
    <li>
        <ol>
            <li>1.</li>
            <li>2.</li>
            <li>3.</li>
            <li>4.</li>
        </ol>
    </li>
    <li>
        <ol>
            <li>1.</li>
        </ol>
    </li><li>
        <ol>
            <li >1.</li>
            <li>2.</li>
        </ol>
    </li><li>
        <ol>
            <li>1.</li>
        </ol>
    </li>
</ol>

Now I want to grab the active class with a selector and want to get the index of this li in relation to all li's. So in this example I should get "5" if it is zero-based.

I tried different things with index(), closest(), parent() and so on with no success. I only get 0 for the active li because it's the first li in "his" ordered list. I think somehow this should be possible and I hope, some of you can give me a hint.

CodePudding user response:

You can use an overload of jQuery's index().

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

So create a collection of all the lis that you're interested in and then pass in the one that you want to find within that collection.

var idx = $("ol>li>ol>li").index($(".active"));

Using just $("li").index($(".active")) would not be enough as you have a number of li around the inner ols, so across "all li" the index would actually be 8.

console.log($("ol>li>ol>li").index($(".active")))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>
  <li>
    <ol>
      <li>1.</li>
      <li>2.</li>
      <li>3.</li>
      <li>4.</li>
    </ol>
  </li>
  <li>
    <ol>
      <li>1.</li>
    </ol>
  </li>
  <li>
    <ol>
      <li >1.</li>
      <li>2.</li>
    </ol>
  </li>
  <li>
    <ol>
      <li>1.</li>
    </ol>
  </li>
</ol>

  • Related