0

I have a page with 2-3 tables. In those tables I want to change the text of a specific column located in <thead> and also a value in each <td> line, and I would like to get the id from each line.

What is the fastest way to do this, performance-wise?

HTML

Table-Layout:

<table class="ms-viewtable">
   <thead id="xxx">
      <tr class ="ms-viewheadertr">
         <th>
         <th>
   <tbody>
      <tr class="ms-itmHover..." id="2,1,0">
         <td>
         <td>
      <tr class="ms-itmHover..." id="2,2,0">
         <td>
         <td>
</table>

JavaScript

Script with that I started:

$('.ms-listviewtable').each(function () {
   var table = $(this);

   $table.find('tr > th').each(function () {
      //Code here
   });

   $table.find('tr > td').each(function () {
      //Code here
   });

How can I get the Id? Is this there a better way to do what I want?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Simon
  • 377
  • 2
  • 11
  • 30

4 Answers4

0

You can get the id of an element by calling .attr on "id" i.e. $(this).attr("id");.

Logan
  • 23
  • 5
0

In jquery the best way to get to any element is by giving it an ID, and referencing it.

I would structure it the other way around - give the table elements meaningful IDs, and then put the information that I'd like to retrieve in their class attributes.

<tr id="ms-itmHover..." class="2,2,0">

And then retrieve it as follows: $('#ms-itmHover...').attr('class');

ForOhFor
  • 786
  • 10
  • 16
0

You can get the IDs by "mapping" from table row to associated ID thus:

var ids = $table.find('tbody > tr').map(function() {
    return this.id;
}).get();

You can access individual cells using the .cells property of the table row:

$table.each('tbody > tr', function() {
    var cell = this.cells[i];   // where 'i' is desired column number
    ...
});
Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

Go thru all tables, collect all rows and locate their identifiers by your needs:

$('table.ms-viewtable').each(function(){
    $(this).find('tr').each(function(){
        var cells = $(this).children(); //all cells (ths or tds)
        if (this.parentNode.nodeName == 'THEAD') {
            cells.eq(num).html('header row '+this.parentNode.id);
        } else { // in "TBODY"
            cells.eq(num).html('body row '+this.id);
        }
    });
});

jsfiddle

Stano
  • 8,749
  • 6
  • 30
  • 44