javascript - getElementsByTagName("table") - getting td on curious way -


i have simple example

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

i wanted first td element of (first) tr element, tried:

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

because it's:

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

that's thought, apparently returns me tr element , adding .children[0]got me td element.

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

why that, or have missed here?

that's because you're forgetting <tbody> element, automatically inserted dom.

what table looks like:

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

hence why needed dig down through 3 levels of children target <td> element wanted.

side note: if you'd know more why <tbody> element automatically injected <table> elements if undeclared, see question , answers.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -