GetElementsByTagName ("table") - getting td in a curious way

I have this simple example

<table border="1px"> <tr> <td> </td> <td> <input type="button" value="Click" onclick="insertText()"/> </td> </tr> </table> 

I wanted to get the first td element of the (first) tr element, I tried:

 var td = document.getElementsByTagName("table")[0].children[0].children[0]; 

Because it:

  • var td = document.getElementsByTagName("table")[0] for the table element itself
  • children[0] for the tr element
  • and children[0] again for the first td element

This is what I thought, but apparently it returns me a tr element and adds another .children[0] , I got a td element.

 var td = document.getElementsByTagName("table")[0].children[0].children[0].children[0]; 

Why is this, or what did I miss here?

+4
source share
1 answer

This is because you forget about the <tbody> element, which is automatically inserted into the DOM.

What your table looks like:

 <table border="1px"> <tbody> <tr> <td> </td> <td> <input type="button" value="Click" onclick="insertText()"/> </td> </tr> </tbody> </table> 

Therefore, you had to slip through the three levels of children in order to target the desired <td> element.

Note: If you want to know more about why the <tbody> element is automatically inserted into <table> elements if they are not declared, see this question and its answers .

+10
source

Source: https://habr.com/ru/post/1491927/


All Articles