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?
Option 1: Just keep going.
document.getElementsByTagName("div")[0].getElementsByTagName("tr")[0].getElementsByTagName("td")[0]
Option 2: querySelector
document.querySelector("div tr td")
querySelector is just like using CSS selectors. You can even select by class or id. Note: if there are more than one elements to select, use querySelectorAll.
As a side note, there's an important difference between document.querySelectorAll("div") and document.getElementsByTagName("div"), in that the former returns a NodeList and the latter returns an HTMLCollection.
Documentation: document.querySelector()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With