Search code examples
javascriptjqueryindexingposition

jQuery element .index() position inside different containers


I need to get the index of an element that shares a class, that it's inside a container, example of code:

<div id="mycontainer">
    <div class="column">Text here</div>
    <div class="column">Text here</div>
    <div class="column">Text here</div>
    <div class="column">Text here</div>
</div>
<div id="mycontainer2">
    <div class="column">Text here</div>
    <div class="column">Text here</div>
    <div class="column">Text here</div>
</div>

I read on the jQuery API of .index() you use it like: $("selector").index(this); All this is fine.

Now, if I don't know the length of .column elements to stop counting the index at certain point, how can I know the first index of each container containing them? I mean, 0 for first column, 1st for second, and 0 for the third one for being in another container, 1st for the fourth.

I need to know it because when mouse enters to a column, it applies some styles, first one and last one of each container having different styles. If I have one container, it's no problem to know it, but the problems comes when there are more than one.

ADD

I've got a class that adds 15% to the width. Now, if it's the first one of each container, it lefts left: 0%, and if its the last one, it's left: 85%;. But, if the column thaat the mouse is pointing a different one, it does the code to add that 15% and keep the column centered.

All this for one container in the page, works as a charm, but if I add a second one, the index of the last column in the first container, is not the last index of column class, so it doesn't adds the left: 85%;, and the same happens to the first one of the second container.


Solution

  • As stated in the .index() doc :

    If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

    So simply doing $(this).index() will give you the element index ammoung its siblings. In other word, its child position.