2

I have table row object in my scope. And I can get it as a link is clicked on that row.

var tableRow = $(object).closest('tr');

What I need is to iterate this table columns of row by table header columns.

For example :

    th1 th2 th3

tr1 td   td   td

tr2 td   td   td*

Lets say, I have tr2 in my scope, and I need to reach at cell under th3. When I iterate its cells, how can I know cell is under th3?

I want to that without using column index, but instead using column name.

2
  • What's wrong with using column index? Using an index is more reliable than using column name—what if the column names are duplicated? Also, can you show us your markup? It's unclear if your table headers are in <thead>, or simple the first row in <tbody>. Commented Jul 15, 2015 at 11:35
  • its because table is a dynamic datatable and user can remove some columns on runtime. Commented Jul 15, 2015 at 11:38

2 Answers 2

1

Iterate through each td of the row context and get the corresponding th of that column using .eq() and .index(). Something like below should work.

In this example I am searching for the column which has a th with text "two"

var $table = tableRow.closest('table');
var query = "two";
var result = tableRow.find('td').filter(function(){
  return $table.find('th').eq($(this).index()).html() === query;
});
console.log(result.html());

$('tr').on('click', function() {
  find($(this));
});

function find(tableRow) {
  var $table = tableRow.closest('table');
  var query = "two";
  var result = tableRow.find('td').filter(function() {
    return $table.find('th').eq($(this).index()).html() === query;
  });
  alert(result.html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <th>One</th>
    <th>two</th>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>3</td>
      <td>4</td>
    </tr>

  </tbody>
</table>

Sign up to request clarification or add additional context in comments.

Comments

1

assuming the id of your table is myTable, you can do:

$("#myTable td")

this will give you all table cells, if you iterate through them you will sweep from cell 1 to N.

if you need only, say the 2nd cell in each row, you can use the following selector:

$("#myTable tr td:nth-child(2)")

this will return you the 2nd cell in each row

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.