my question is: How can I make a table cell, for example, change text on click?
I tried this:
function randomFunction() {
document.getElementById("randomId").innerText = "random text"
}
<table>
<tr>
<td id="randomId" onclick="randomFunction()">random text</td>
</tr>
</table>
but it does the onclick attribute for the entire row.
Is it possible to trigger the function only when I click on the cell ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Yes it possible. you have pass the context to the function. I put more cells in your table.
function randomFunction(e){
e.innerText = "HuhU"
// document.getElementById("randomId").innerText = "random text!"
}
td {
background: green;
color:white;
}
<table>
<tr>
<td id="randomId" onclick="randomFunction(this)">random text</td>
<td id="randomId" onclick="randomFunction(this)">random text</td>
<td id="randomId" onclick="randomFunction(this)">random text</td>
</tr>
</table>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0