xonorageous xonorageous - 1 year ago 71
jQuery Question

Traversing multiple html tables with jQuery

I've got a couple of HTML tables that are similar in structure. They both look something like this:

<table cellspacing="1" cellpadding="7" summary="Procedure Tabulate: Table 1" frame="box" rules="groups" class="table table-bordered table-hover highchart-table">
<th scope="col" rowspan="2" class="c m Header">&nbsp;</th>
<th scope="col" class="c Header">3</th>
<th scope="col" class="c Header">CA R</th>
<th scope="row" class="l t RowHeader">Fours</th>
<td class="r b Data">10268.64</td>
<th scope="row" class="l t RowHeader">Hifi</th>
<td class="r b Data">11267.82</td>
<th scope="row" class="l t RowHeader">Magneto</th>
<td class="r b Data">11575.91</td>
<tr class="blue-bg">
<th scope="row" class="l t RowHeader">Total</th>
<td class="r b Data">33112.36</td>

I would like to run through all the tables with a class of highchart-table and retrieve CA R (last cell of last row of thead) and create associative arrays with the th and td inside tbody apart from the final "total line" ( ex: Fours => 10268.61, Hifi => 11575.91, Magneto => 11575.91 ).

My final goal would be to create an array something like this:

hcArr[0]['ind'] = 'CA R';
hcArr[0]['Fours'] = 10268.61;
hcArr[0]['Hifi'] = 11575.91;
hcArr[0]['Magneto'] = 11575.91;

And then have
which contains the contents of the next table with a class of

For the moment the only code I have that is working is:

$.each( $( '.highchart-table' ), function( key, value ) {


I can't figure out how to then go from having the table in the current loop to getting it's rows and cells.

Any help would be much appreciated.

Answer Source

Something like this should work:

var res = [];

$(".highchart-table").each(function() {
  var $$ = $(this), obj = {};
  obj.ind = $(this).find('thead tr:last th:last').text();
  $$.find("tbody th").each(function(){
    obj[$(this).text()] = parseFloat($(this).siblings("td").text());


By the way, arrays in javascript are only numeric indexed, so it would return an array of objects like this:

  { "ind": "CA R", "Fours": 10268.64, "Hifi": 11267.82, "Magneto": 11575.91 },
  { "ind": "CA R", "Fours": 10268.64, "Hifi": 11267.82, "Magneto": 11575.91 },
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download