Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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?

like image 440
M Smith Avatar asked Dec 14 '25 02:12

M Smith


1 Answers

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()

like image 156
Andrew Avatar answered Dec 16 '25 02:12

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!