I'd like to use JavaScript to add rows to a table. It seems like an easy idea, but it occurs to me that the parent node of the rows might technically be a TBODY element. So, I'm wondering if I use appendChild to add a table row to a table element am I doing something wrong and, more importantly, is it going to fail in browser x?

For example:

function addTheRow() {
	var myTable = document.getElementById('myTable');
	var newRow  = document.createElement('TR');
	var newCell = document.createElement('TD');
	newCell.appendChild( document.createTextNode('Yeah, Baby! Yeah!!') );
	newRow.appendChild( newCell );

	myTable.appendChild( newRow );
} // End addTheRow function

Should I do something to identify the TBODY element and add the element to that instead?

Thank you.

-- Ghodmode

8 Years
Discussion Span
Last Post by codejoust

Do-- document.getElementById('myTable').getElementsByTagName('tbody')[0] to get the tbody instead of the whole table if you want to.
Typically, browsers will try to 'fix' your markup by automatically inserting tbody.

Edited by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)

Votes + Comments
exactly what I needed
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.