Search code examples
javascriptjquerytraversal

How to use javascript/jquery to loop through table?


I have a block of code like below

<tbody class="society_list">
    <tr>
        <td>1</td>
        <td>Dummy</td>
        <td>Dummy</td>
        <td id="lol0">UPDATE THIS</td>
    </tr>
    <tr>
        .....
    </tr>
</tbody>

What I want to do is to loop through the whole table, find the td with an id, get the value of that id, and then update the html inside. What I have for now(Sorry I'm quite new and I still don't have much idea what to do...)

function update(){
  var trs = document.querySelectorAll('.society_list tr');
  for(i=0;i<trs.length-1;i++){
    trs[i].find('td').each(function(){
      //I know I need to do something here but what's that.. 
    });
  }
}

Solution

  • Iterate through tds which have id attribute using the has attribute selector.

    $('.society_list tr td[id]').each(function(){
      var tdID = $(this).attr('id'); // <--- getting the ID here
      var result = doSomeMagicWithId(tdID); // <--- doing something
      $(this).html(result);  // <---- updating the HTML inside the td
    });