necromonger said:
Thanks ROb. You've mentioned I should "insert" the row into the table,
how do I do that? isnt appendChild doing it already (internally?)
[snip]
Read Richard's post below. I'd figured the bit about the TBODY from
the tree display, but only on the bus home from work. So Richard gave
me the heart to try again. So the add row function now has a findTbody
function too - it gets the first TBODY after the TABLE reference that
you pass. The reason you need this is because you can't guarantee that
the first child of a table will be a tbody - in Safari and Firefox it's
a text node.
If you have a row ref, it's simpler to use the insertBefore/nextSibling
method.
Here's some code anyway, and have fun. I've added comments as
appropriate, you may wish to trim them out.
Oh, I added an index to the showDOM function to make it easier to tell
children and siblings.
<html>
<head>
<title>Insert Row</title>
<script type="text/javascript">
// Add a row to a table
function addRow1(stbl) {
// find the first tbody tag
var tB = findTbody(stbl);
// create the elements
var newr = document.createElement('tr');
var newc = document.createElement('td');
// append the HTML to the td
newc.innerHTML = "blah blah blah <br><hr>";
// append the td to the tr
newr.appendChild(newc);
// append the tr to the tbody
tB.appendChild(newr);
}
// Pass a tableRef and returns the first tBody
function findTbody(t) {
function readTree(u) {
for (var j=0; j<u.childNodes.length; j++) {
if (u.childNodes[j].nodeName == 'TBODY') {
// break out if we found a tbody
return u.childNodes[j];
}
// otherwise keep looking
readTree(u.childNodes[j]);
}
}
var x = readTree(t);
return x;
}
// shows the DOM with index
// only good for IE as other DOM
// viewers are better
function showDOM() {
var msg = "";
function listNodes(n,x) {
msg += x + ' ' + n.nodeName + "\n";
for (var i=0; i<n.childNodes.length; i++) {
listNodes(n.childNodes
,x + '.' + i);
}
}
listNodes(document.getElementById("aTable"),'0');
alert(msg);
}
// demonstrates adding a row after a row
// using insertBefore/nextSibling method
function addRow2(r) {
var newr = document.createElement('tr');
var newc = document.createElement('td');
newc.innerHTML = "blah blah blah <br><hr>";
newr.appendChild(newc);
var rParent = r.parentNode;
rParent.insertBefore(newr,r.nextSibling);
}
</script>
</head>
<body>
<table id="aTable" border="1">
<tr id="aRow"><td>Here is aRow</td></tr>
</table>
<br>
<form action="" name="aForm">
<input type="button" value="add row 1" onclick="
addRow1(document.getElementById('aTable'));
">
<input type="button" value="add row 2" onclick="
addRow2(document.getElementById('aRow'));
">
<input type="button" value="Show DOM tree"
onclick="showDOM();">
</form>
</body>
</html>