0

The following code works just fine, and I am able to get the value of the first cell of a selected row:

document.getElementById("tst").onclick = function() {
  var chosen = document.getElementsByClassName('selected');
  var myTd = chosen[0].getElementsByTagName('td');
  var rightCell = myTd[0];
  console.log(rightCell.innerHTML);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>table_js_test002.html</title>
  <link href="css/test_table.css" rel="stylesheet">
</head>

<body>

  <table id="table">
    <tr>
      <td>1 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>

    </tr>
    <tr class="selected">
      <td>2 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>

    </tr>
    <tr>
      <td>3 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>

    </tr>
  </table>
  <input type="button" id="tst" value="OK" onclick="fnselect()" />


</body>

</html>

This also works:

var myTd = chosen[0].cells[0].innerHTML; 

My question is, from my limited understanding of JavaScript and DOM Node Navigation, isn't <td> a child of <tr>? Why can't I get

var myTd = chosen[0].firstChild.innerHTML 

to work?

ksav
  • 20,015
  • 6
  • 46
  • 66
CodeSchlocker
  • 61
  • 1
  • 1
  • 7
  • 1
    Please remove the preamble and references to other users/questions. Ask your question in the most straight forward manner possible, with no back story, and the shortest **runnable example** that reproduces your problem. – user229044 Nov 24 '20 at 01:11
  • OK. DIdn't want to steal someone elses code, as simple as this piece of HTML is without giving due credit. – CodeSchlocker Nov 25 '20 at 05:41

2 Answers2

5

Per MDN, when using firstChild:

Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.

Just use firstElementChild:

myTd = chosen[0].firstElementChild.innerHTML
yaakov
  • 4,568
  • 4
  • 27
  • 51
  • 1
    It's worth noting, if you write your HTML all smushed up, `etc`, the TD can be the first child. Just... no one does that, because we like ourselves. The "problem" here is the whitespace in the code, not the API. – Chris Baker Nov 24 '20 at 01:18
1

The issue is getElementsByTagName returns a HTMLCollection, not a NodeList. Both are array like object but HTMLCollection contain elements and firstChild only works on nodes.

If you want more details about the two

NodeList vs HTMLCollection

Node vs Element

Scot
  • 59
  • 7