I’m a hobby coder and struggle with following issue:
I got a table element with a few rows, each row 3 cells. Via a button at the bottom I would like to add rows. The table looks like this:
<table id="mytable">
<tr id="line[0]"><td id="cellA[0]"</td><td id="cellB[0]"</td><td id="cellC[0]"</td></tr>
<tr id="line[1]"><td id="cellA[1]"</td><td id="cellB[1]"</td><td id="cellC[1]"</td></tr>
<tr id="line[2]"><td id="cellA[2]"</td><td id="cellB[2]"</td><td id="cellC[2]"</td></tr>
</table>
I loop through with elementbyID “line” to find that the last line is [2]. And then add a new line like this:
var table = document.getElementById("mytable");
var row = table.insertRow(oldID + 1);
row.setAttribute("id","line["+ oldID + 1 + "]");
This works great.
Next I get the content of the last line via var lastLine = document.getElementById(oldID).innerHTML. Now since the td IDs are cellA[2], cellB[2] and cellC[2]. I would like to replace those with [3].
I tried following:
var oldVar = "[" + oldID + "]";
var newVar = "[" + oldID + 1 + "]";
var regex = new RegExp(oldVar, "g");
var neueLine = lastLine.replace(regex, newVar);
but this results in ids like this “cellA[3][3]”, “cellB[3][3]” and “cellC[3][3]”.
I feel like my limited knowledge is missing out on the supposed way to do this.
Thanks a lot for your help!