Search code examples
javascripthtmlclassinnerhtmltr

Javascript to get text node of td using tr class


I have the following codes below:

<table>
  ...
[Multiple lines ommited for brevity]

<tr class="bibItemsEntry"> 
<td width="31%" ><!-- field 1 -->&nbsp;Archives, Thesis Col. Graduate, 12F (Mezz.) Henry Sy Sr. Hall 
</td>
<td width="46%" ><!-- field C -->&nbsp;<a href="/search~S1?/cCDTG006829/ccdtg006829/-3,-1,,E/browse">CDTG006829</a> <!-- field v --><!-- field # -->&nbsp;<!-- field ! -->&nbsp;ROOM USE ONLY</td>
<td width="23%" ><!-- field % -->&nbsp;CHECK SHELF </td></tr>
</table>

<p id="demo">Test</p>

What I wanted to do is to use javascript and get the first value of the text node of <td> under <tr class="bibItemsHeader">. I'm trying to put the value into <p id="demo">. I'm trying out the below javascript code:

var x = document.getElementsByClassName("bibItemsEntry");
document.getElementById("demo").innerHTML = x[0].innerHTML;

But I'm getting all the td text node values. Can somebody help with my problem? Thanks in advance!


Solution

  • You are selecting the tr element and not the first td that you really want. Try this:

    const td = document.querySelector('.bibItemsEntry td:first-child');
    const p = document.getElementById('demo');
    p.innerHTML = td.textContent;