menteith menteith - 12 days ago 6
Javascript Question

Retriving data from a table in HTML by using nextSibling

I have two tables in HTML:

<tr>
<td width="319" align="right" bgcolor="#F5F5F5" class="txtdarkgreybold">Article title:</td>
<td width="346" align="left" bgcolor="#F5F5F5">My title</td>
</tr>
<tr>
<td align="right" class="txtdarkgreybold">Author:</td>
<td align="left"><a href="/index.php?action=search&amp;name1=Przylipiak Mirosław&amp;results=10">Doe John</a><br /></td>
</tr>


By using
document.getElementsByClassName("txtdarkgreybold")
I can retrieve string
Article title:
but I am interested in what comes after it, that is:
My title
. How do I do this? In the second table I can get
Author:
but I am interested in
Doe John
. I was thinking about
nextSibling
as a way to get the strings that come after string I can get but I cannot implement it on my own.

Answer

You could use nextElementSibling with textContent :

document.querySelector('.txtdarkgreybold').nextElementSibling.textContent

Hope this helps.

console.log( document.querySelectorAll('.txtdarkgreybold')[0].nextElementSibling.textContent );

console.log( document.querySelectorAll('.txtdarkgreybold')[1].nextElementSibling.textContent );
<table>
  <tr>
    <td width="319" align="right" bgcolor="#F5F5F5" class="txtdarkgreybold">Article title:</td>
    <td width="346" align="left" bgcolor="#F5F5F5">My title</td>
  </tr>
  <tr>
    <td align="right" class="txtdarkgreybold">Author:</td>
    <td align="left"><a href="/index.php?action=search&amp;name1=Przylipiak Mirosław&amp;results=10">Doe John</a><br /></td>
  </tr>
</table>