Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling tbody when adding rows to an empty table with jQuery

I have an empty table in my code like so:

<table id='rostertable'></table>

When I add a <tr> using jQuery's append function, then according to my chrome inspector, my table looks like this:

<table id='rostertable'><tbody><tr>...</tr></tbody></table>

It seems like the tbody got added by itself, and this causes problems later when I'm traversing the DOM.

For consistency's sake, I figured it would be better if I added the tbody myself and appended directly to it. Is this possible? I tried making my placeholder <table id='rostertable'><tbody></tbody></table> but the jQuery selector $('#rostertable tbody') returns null and my chrome inspector doesn't show the tbody tags either.

Edit: Never mind, it ended up being an unrelated bug in my javascript. At one point I was clearing out the contents of the table and running $("#rostertable").html(""), which of course deleted the tbody. I accepted the first valid answer to this question.

like image 381
khalid13 Avatar asked Dec 22 '12 03:12

khalid13


2 Answers

You should not get null, if no element matches the selector still you will get object containing zero elements.

Your selector is returning tbody and you might be using some wrong method.

Live Demo

alert($('#rostertable tbody').html());​
like image 126
Adil Avatar answered Sep 28 '22 00:09

Adil


To append to the tbdoy your code should work as long as you append valid html.

The below works ok:

$('#rostertable tbody').append('<tr><td>new row - cell 1</td><td>new row - cell 2</td></tr>');

DEMO

You need to make sure you append a <td> as well as the <tr>. For example in Chrome, the following will simple add an empty <tr>

$('#rostertable tbody').append('<tr>no cells added, just row</tr>');​
like image 28
Nope Avatar answered Sep 28 '22 00:09

Nope