Is it possible to replace all the contents of the first row of an HTML table without assigning an ID to each <td> element?

I have a simple html table consisting table headers and a first row as shown below:

<html>
<table>
<thead>
<th>name</th>
<th>email</th>
</head>
<tr>
<td>Kipchoge</td>
<td>k@gmail.com</td>
</tr>
</table>

<input type="button" id="btn" value="btn" onClick="fn()"/>
</html>

How can I change all the contents of the first row with my custom text when I click the button?
I have tried assigning my new text directly to document.getElementByTagName("tr")[1].innerHTML with no success as shown in the code below:

function fn(){
var d = document.getElementsByTagName('tr');
var customtext = "";
d[1].innerHTML = customtext;
}
<table>
<thead>
<th>name</th>
<th>email</th>
</head>
<tr>
<td>Kipchoge</td>
<td>k@gmail.com</td>
</tr>
</table>
<input type="button" id="btn" value="btn" onClick="fn()"/>

I know that what I have done in the above code is trying to assign a new value to an existing innerHTML value which can be easily achieved when you use getElementById, but my idea is to change all the values of the first row once without assigning an id to each <td></td>.
Is there an alternative approach? Or what should I do to my approach in order to solve such a problem?

I tried changing existing innerHTML with new text as shown below:

d[1].innerHTML = customtext;

But that did not work.

>Solution :

The function getElementsByTagName returns an array of elements. In your code you are trying to add text inside a table row node. Table row – or tr – is only allowed to have td elements inside it. In the following example, I am using innerHTML to set HTML that represents the that contains the td with the text inside them.

function fn(){
  var tr = document.getElementsByTagName('tr')[0];
  tr.innerHTML = `<td>Text 1</td><td>Text 2</td>`;
}
<table>
  <thead>
    <th>name</th>
    <th>email</th>
  </thead>
  <tr>
    <td>Kipchoge</td>
    <td>k@gmail.com</td>
  </tr>
</table>

<input type="button" id="btn" value="btn" onClick="fn()"/>
</html>

Leave a Reply