use JQuery to query HTML row

Simon Leung
Simon Leung used Ask the Experts™
on
Is there any example on using JQuery to display each column of a selected row in a HTML table ?

Thx
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Brian TaoOwner
Top Expert 2014

Commented:
Yes, give the table an ID (e.g. "theTable") or use other selector, and the following code can do the trick:
$(document).ready(function(){
  $("#theTable tr").click(function(e){
    var result = "";
    $.each($(this).children(), function(idx, obj){
      result += idx + ": " + $(obj).text() + "\n";
    });
    $("#resultText").val(result);
  });
});

Open in new window

see attached example
test-29164240.html
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
The DOM provides us with some neat methods and properties to make this a lot easier.

If you have to support IE 11 or less then
<script>
$(function() {
  // optionally refine selector using class or id
  $('table tr').click(function() {
    for(var i = 0; i < this.cells.length; i++) {
      console.log(this.cells[i].innerHTML);
    }
  });
});
</script>

Open in new window

If you only intend to support standards compliant browsers then you can do this
<script>
$(function() {
  // optionally refine selector using class or id
  $('table tr').click(function() {
    for(const cell of this.cells) {
      console.log(cell.innerHTML);
    }
  });
});
</script>

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial