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>[email protected]</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>[email protected]</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.
3
Answers
Use the more powerful
querySelector
method to select elements from the DOM by using CSS Selectors. In your case you can select the first row withtbody tr:first-of-type
.The function
getElementsByTagName
returns a live HTMLCollection which is an array-like-object of elements. In your code you are trying to add text inside a table row node. Table row – ortr
– is only allowed to havetd
elements inside it. In the following example, I am usinginnerHTML
to set HTML that represents the that contains thetd
with the text inside them.You can iterate over the table heads in this way