Praveen Praveen - 5 months ago 10
jQuery Question

difference between $(this).index() and element.index(this)

I was trying to get the index of input box using

$(this).index()
and was getting wrong index.

After finding in Google applied
$("input").index(this)
and it worked. So curious to know what is the difference in these two methods and why the earlier one has not worked.

Answer

$(this).index() will return the index with respect to the parent element.

$("input").index(this) returns the index of the passes item based on the set of elements on which .index() was called.

consider this HTML

<table>
  <tr>
    <td>
      <input type="text">
    </td>
  </tr>
  <tr>
    <td>
      <input type="text">
    </td>
  </tr>
</table>

Then the code,

$("input").click(function() {
  alert($(this).index());
  alert($("input").index(this));
});
  • alert($(this).index()); will always alert 0, because its the one and only child element of its parent TD.
  • alert($("input").index(this)); will return 0 for the first input and 1 for the next input.

Check this Demo

Comments