MarkokraM
MarkokraM

Reputation: 990

How to get index of element by parent in JQuery

I want to get index of div element from parent tree:

$(".row .col a").click(function() {
  var e = $(this).parent();
  var p = e.parent();
  var i = p.index(e);
  console.log([e, p, i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="row">
    <div class="col"><a>link 1</a>
    </div>
    <div class="col"><a>link 2</a>
    </div>
  </div>
</div>

But index is always -1. First link should be 0 and second link 1. How do you get index in this kind of html sctructure?

Upvotes: 3

Views: 3284

Answers (1)

Tushar
Tushar

Reputation: 87203

index() get the index of the element in the parent. As there is only one element with .row class, index() returns the index 0 as it is zero-based.

To get the index of the clicked element, get the closest ancestor .col and call index on it.

$(this).closest('.col').index()

Demo

$(".row .col a").click(function() {
  console.log($(this).closest('.col').index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="row">
    <div class="col"><a>link 1</a>
    </div>
    <div class="col"><a>link 2</a>
    </div>
  </div>
</div>

Upvotes: 5

Related Questions