Search code examples
javascripthtmlcsssimple-html-dom

Change table td using javascript


I am new to Javascript so take it easy on me. I want to change data inside a table using javascript. I have looked everywhere for a suitable tutorial but I haven't found any. This is my code.

function trans() {
  var table = document.getElementById("table");
  var row = table.getElementsByTagName("tr")[2];
  var td = row.getElementsByTagName("td")[0];

  td.innerHTML = "Julius";
}
**css**
table {
  width: 100%;
  border-collapse: collapse;
  font-family: calibri;
}
tr,
th,
td {
  border: 2px solid black;
  padding: 10px 10px 10px 10px;
}
thead {
  background-color: black;
  color: white;
}
tbody {
  background-color: white;
  color: black;
}
.center {
  text-align: center;
}
.caption {
  text-align: center;
}
button {
  background-color: blue;
  color: white;
  border-radius: 5px;
  height: 25px;
}
<html>

<body>
  <table id="table" title="Employment status verses Living Conditions">
    <caption>Employment status verses Living Conditions</caption>
    <thead>
      <tr>
        <th colspan="3" class="caption">Employment status verses Living Conditions</th>
      </tr>
      <tr>
        <th>Name</th>
        <th>State</th>
        <th>Condition</th>
      </tr>
    </thead>
    <tr>
      <td>Antony</td>
      <td>Employed</td>
      <td>Poor</td>
    </tr>
    <tr>
      <td>Grace</td>
      <td>Student</td>
      <td>Wealthy</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>Sponsored</td>
      <td>Self actualization</td>
    </tr>
    <tr>
      <td>Christine</td>
      <td colspan="2" class="center"><i>Unknown</i>
      </td>
    </tr>
    <tr>
      <td rowspan="2">James and John</td>
      <td>Fishermen</td>
      <td>Spiritual</td>
    </tr>
    <tr>
      <td>Brothers</td>
      <td>Disciples</td>
    </tr>
  </table>
  <button onclick="trans()">Change name</button>
</body>

</html>

When I run the code it gives me the following error,

  {
  "message": "Uncaught TypeError: table.getElementByTagName is not a function",
  "filename": "http://stacksnippets.net/js",
  "lineno": 96,
  "colno": 15
}

I have changed the getElementByTagName to getElementsByTagName but it is still giving me an error, What is wrong with my code and what can I do to fix it. Find my jsfiddle here


Solution

  • This works: Code snippet
    Try this:

    function trans() {
      var table = document.getElementById("table");
      var row = table.getElementsByTagName("tr")[2];
      var td = row.getElementsByTagName("td")[0];
    
      td.innerHTML = "Julius";
    }
    

    You selected the first tr that has no td , only th in it and you also forgot "s" in "getElementsByTagName".

    Because with "Tag" you can get more then 1 element you need to add "s" , when it's by ID it makes sense that you will get only 1 item therefor no "s" is needed.