D Cooper D Cooper - 29 days ago 5
Javascript Question

How can I select a nested element without an id or class?

For example, suppose I had the following HTML:

<div>
<table>
<tr>
<td>X</td>
<td></td>
</tr>
</table>
</div>

<div></div>


and I wished to fin the value within the td element with an X in it.
I know that I would obviously use

var foo = document.getElementsByTagName("TD")[0].innerHTML;


in order to select that specific td element, and not one of the others.
However, given that I know the path to the element, how can javascript be used in this way to select this particular value?

Answer

you should first get the tr

var tr = document.getElementsByTagName("tr")[0];
var foo = tr.getElementsByTagName("td")[0].innerHTML;
console.log(foo);
<div>
<table>
<tr>
<td>X</td>
<td></td>
</tr>
</table>
</div>

<div></div>

Comments