getElementByTagName() not working?

15,428

Solution 1

As with most DOM methods that return a Node list, the name is plural - getElementsByTagName.

Solution 2

It is document.getElementsByTagName - plural form!

Because it has the possibility to return multiple elements in a NodeList - hence Elements.

Solution 3

document.getElementsByTagName "PLURAL"

Solution 4

use

document.getElementsByTagName("table")[2]; instead of document.getElementByTagName("table")[2];

Share:
15,428
Nikhil
Author by

Nikhil

I love to create products which solve problems.

Updated on June 21, 2022

Comments

  • Nikhil
    Nikhil almost 2 years
    1. In my page I've got 3 table elements, I want to access the 3rd element using its tagname.

      So, I used document.getElementByTagName("table")[2];

    2. Later, I tried to obtain value of an element in that table by table.children[0].children[1].children[2].innerHTML;

    3. Then, I tried to modify the already existing <p>element with id="ID" .

      But I'm not getting the value modified?

    Whats wrong with my script?

    <!DOCTYPE HTML>
    
    <html>
      <body>
        ID  : <p id="ID"></p>
     <body>
    <table>
      
    </table>
    <table>
      
    </table>
    
    <table>
      <tbody>
      <tr>
      
      </tr>
      <tr>
        <td>Name</td>
        <td>Class</td>
        <td>25</td>
      </tr>
      <tr>
      
      </tr>
      </tbody>
    </table>
    
    <script>
    
    var table = document.getElementByTagName("table")[2];
     var id = table.children[0].children[1].children[2].innerHTML;
     
    document.getElementById("ID").innerHTML = id;
        
        </script>
     </body>
    </html>