view raw
Praveen Praveen - 11 months ago 42
jQuery Question

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

I was trying to get the index of input box using

and was getting wrong index.

After finding in Google applied
and it worked. So curious to know what is the difference in these two methods and why the earlier one has not worked.


$(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

      <input type="text">
      <input type="text">

Then the code,

$("input").click(function() {
  • 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