0

I'm trying to reference a th relating to a td within the same tr, unfortunately the headers and classes do not correspond so I cannot just create another .each loop.

I've had a play with adapting this answer which references a vertical heading but with no success.

Thanks all for your help.


Example Row

<tr>
<th id="row_51_18" class="level3 levelodd item b1b column-itemname" colspan="1"><a title="Link to Quiz activity" href="http://virtualmedics.org/mod/quiz/grade.php?id=93&amp;itemnumber=0&amp;userid=18"><img class="icon itemicon" alt="Quiz" title="Quiz" src="http://virtualmedics.org/theme/image.php?theme=vmelegance&amp;amp;component=quiz&amp;amp;image=icon">Acute Appendicitis</a></th>
<td headers="cat_23_18 row_51_18 percentage" class="level3 levelodd item b1b itemcenter  column-percentage">79 %</td>
<td headers="cat_23_18 row_51_18 average" class="level3 levelodd item b1b itemcenter  column-average">65 %</td>
<td headers="cat_23_18 row_51_18 feedback" class="level3 levelodd item b1b feedbacktext column-feedback">&nbsp;</td>
</tr>

Javascript

$("[id^=cat_]").each(function(i,obj){


var gatherLabels = [];
var gatherValues = [];


$('td[headers*="' + obj.id + '"]').each(function(i, obj) {

    if ($(obj).hasClass("column-percentage")) {
        gatherLabels.push(obj.closest('tr').child('th').innerText); // 'undefined'
        gatherValues.push(obj.innerText.replace('%', '')); // Working fine
    }

});

Questions

  1. How can I select the text within the corresponding th for each td
  2. Is declaring obj twice (within both .each) an awful thing to do.... seems to not matter
Community
  • 1
  • 1
Oliver Trampleasure
  • 3,293
  • 1
  • 10
  • 25

1 Answers1

3

Given that within the .each call the variable obj is a plain DOM <td> element, and that the <th> is the first (element) child of the enclosing <tr>:

var th = obj.parentNode.firstElementChild;

As th is also a plain DOM element you can continue to access its innerText attribute directly.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    Do be aware that `firstElementChild` is not supported before IE9 - see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/firstElementChild – Alnitak Jan 04 '16 at 12:16