Reputation: 82297
Is it possible to replace a table cell without deleting it with javascript or jQuery? For example, if I have a table with several rows, each row having 5 cells, could I change the first cell of the first row through assignment instead of removing the cell and then inserting a new one?
EDIT (simplified):
<table>
<tr id="currentRowId1" name="currentRowId1">
<td style="text-align:center">
</td>
<td style="text-align:center">
</td>
<td style="text-align:center">
<input type="submit" onclick="changeOrder()" />
</td>
<td style="text-align:center">
</td>
<td>
</td>
</tr>
<tr id="currentRowId2" name="currentRowId2">
<td style="text-align:center">
</td>
<td style="text-align:center">
</td>
<td style="text-align:center">
<input type="submit" onclick="changeOrder()" />
</td>
<td style="text-align:center">
</td>
<td>
</td>
</tr>
</table>
js
function changeOrder(){
var row = document.getElementById("currentRowId1");
var otherRow = document.getElementById("currentRowId2");
row.cells[0] = otherRow.cells[0];
}
Upvotes: 3
Views: 4935
Reputation: 54659
There is acutally no need to work with innerHTML
here. You could replace the two elements like this:
var
a = document.getElementById('currentRowId1').cells[0],
e = document.getElementById('currentRowId2').cells[0],
e1 = e.nextSibling;
a.parentNode.replaceChild(e, a);
e1.parentNode.insertBefore(a, e1);
demo: http://jsfiddle.net/X4zzb/1/
Upvotes: 3
Reputation: 18786
There are multiple ways to do this. You can set the inner html of the cell as fabianhjr pointed out. You can also build a new element in javascript/jquery and use jquery's replaceWith() method.
You can use other jquery methods that will replace the cells, clone() and before() or after() I know this isn't what you asked for just pointing out other options.
Example #1:
var me = $("#cellId");
var newHtml = $("<div>blah blah blah</div>");
me.replaceWith(newHtml);
Example #2:
var me = $("#cellId");
var clone = me.clone();
// do some cool things with the clone change html whatever
me.replaceWith(clone);
Upvotes: 1
Reputation: 150080
You can't just assign the cell equal to something else like you tried in this line:
row.cells[0] = otherRow.cells[0]; // doesn't work
However, once you have a reference to the cell you can change what is inside it, e.g., to copy the contents from one cell to another:
row.cells[0].innerHTML = otherRow.cells[0].innerHTML;
You can also create, amend or remove the children of the cell via the reference to the cell.
If you are using jQuery there are a number of methods that achieve the same sort of thing, e.g., the following is equivalent to the above (but less efficient):
$(row.cells[0]).html( $(otherRow.cells[0].html() );
Upvotes: 0
Reputation: 10712
If you just want to change whats inside it you can use..
document.getElementById('nameofyourcell').innerHTML = 'content';
Upvotes: 0