JQuery or javascript element index

I have a table containing 3 columns. I need to bind an event that fires every time I click on one of these columns using jQuery.

However, I need to know the index of the clicked column.

ie: First column (index 0), Second column (index 1), Third column (index 2), etc ...

How can i do this?

var firstRow:

var firstRow = $("tr:first > th", "table[id*=Grid]");

Take a look:

firstrow.click(function(e){
//var id = e.target.index;
var id = $(e).parent().children().index(this);//returns -1
})
+5
source share
3 answers

You can do this using .index()(based on 0):

$("td").click(function() {
  var i = $(this).parent().children().index(this);
  alert(i);
});
+6
source

It might be better to use native javascripts .rowIndexinstead of jQuerys .index. jQuery may have some problems finding head head (TH) elements.

+2

.prevAll()

$('table').click(function(e) {
  var $targ = $(e.target);
  if ($targ.is('th')) {
    var position = $targ.prevAll().length;
    alert(position);
  }
});

jsbin

0

All Articles