简体   繁体   中英

JQuery loop through table get ID and change values in a specific column

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?

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

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');

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
    ...
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM