Skip to content

Error assigning functions parameters in a javascript function to modify a table cell

I got these two errors:

Uncaught TypeError: Cannot read properties of null (reading ‘rows’) at changeContent

Uncaught TypeError: Cannot read properties of null (reading ‘rows’) at changeContent

when trying to run the below code.

function changeContent(r, c, con) {
    var row = document.getElementById('myTable').rows[r].cells;
    row[c].innerHTML =con;
}

changeContent(0, 0, "changed");
<!DOCTYPE html>
<html><head><meta charset=utf-8 />
<title>Change the content of a cell</title>
<script src="index.js"></script>
</head><body>
<table id="myTable" border="1">
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
<tr><td>Row3 cell1</td>
<td>Row3 cell2</td></tr>
</table><form>
<input type="button" onclick="changeContent()" value="Change content">
</form></body></html>

How can I rectify this? Thank you.

Edit: I finally found something that works:

function changeContent(r=0, c=1, con="changed") {
var row = document.getElementById('myTable').rows[r].cells;
row[c].innerHTML =con;

}

Answer

You can try to do this in a way you want/need some user input. As such it will be only able to change according to that Beyond that you must have to feed some data:

function changeContent()
{
rn = window.prompt("Input the Row number(0,1,2)", "0");
cn = window.prompt("Input the Column number(0,1)","0");
content = window.prompt("Input the Cell content");  
var x=document.getElementById('myTable').rows[parseInt(rn,10)].cells;
x[parseInt(cn,10)].innerHTML=content;
}
<html> 
<head> 
<meta charset=utf-8 /> 
<title>Change the content of a cell</title> 
<style type="text/css"> 
body {margin: 30px;} 
</style>  
</head><body> 
<table id="myTable" border="1"> 
<tr><td>Row1 cell1</td> 
<td>Row1 cell2</td></tr> 
<tr><td>Row2 cell1</td> 
<td>Row2 cell2</td></tr> 
<tr><td>Row3 cell1</td> 
<td>Row3 cell2</td></tr> 
</table><form> 
<input type="button" onclick="changeContent()" value="Change content"> 
</form></body></html>