Append children without a parent

Think how twitter appends a chunk of list items to the end of the list when you load more results.
I’m trying to achieve the same thing without replacing the entire parent with the same content each time ‘appendRows1()’

The function needs to support any type of content - the children could be tr’s li’s etc.

Or is the first version fine?


<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>js</title>
</head>
<body>
<script>
function appendRows1() {
	var tbody = document.getElementById('tbody');
	tbody.innerHTML = tbody.innerHTML + '<tr><td>a</td><td>b</td></tr><tr><td>a</td><td>b</td></tr><tr><td>a</td><td>b</td></tr>';
}

function appendRows2() {
	var tbody = document.getElementById('tbody');
	var div = document.createElement('div');
	div.innerHTML = '<tr><td>a</td><td>b</td></tr><tr><td>a</td><td>b</td></tr><tr><td>a</td><td>b</td></tr>';
	var children = div.childNodes;
	console.log(children);
	for (var i=0, ii=children.length; i<ii; i++) {
		tbody.appendChild(children[i]);
	}
}
</script>
<table>
  <tbody id="tbody">
  	<tr><td>a</td><td>b</td></tr>
    <tr><td>a</td><td>b</td></tr>
    <tr><td>a</td><td>b</td></tr>
  </tbody>
</table>
<p><a href="#" onclick="appendRows1(); return false;">appendRows1()</a></p>
<p><a href="#" onclick="appendRows2(); return false;">appendRows2()</a></p>
</body>
</html>

Thanks,

You can use the method “insertRow” of the table object, like in this example.
As you can see, the table row object has a method named “insertCell”.

Thanks Amit, the problem is that I don’t know they will rows, and I don’t know how to iterate through a list of child elements from an HTML string.


<parent>
  <child></child>
  <child></child>
  /* insert HTML string here */
</parent>

Any other ideas?

Here’s the solution I came up with, I don’t think the first version could have possibly worked in IE so I think I’ll use this one which uses appendChild.


function toArray(list) {
    var arr = [];
    for (var i = 0, ii = list.length; i < ii; i++) {
        arr.push(list[i]);
    }
    return arr;
}
function appendRows(parent, html) {
    var tag = html.substr(html.indexOf('<')+1, html.indexOf('>')-1);
    if (tag == 'tr') {
        elm = document.createElement('div');
        elm.innerHTML = '<table><tbody>'+html+'</tbody></table>';
        elm = elm.childNodes[0].childNodes[0];
    }
    else {
        elm = document.createElement(tag);
        elm.innerHTML = html;
    }
    children = toArray(elm.childNodes);
    for (var i=0, ii=children.length; i<ii; i++) {
        parent.appendChild(children[i]);
    }
}