Jump to content

insertRow in a table that has a thead/tbody


SteveBaker

Recommended Posts

I have an initially empty table with headings, like this:

 

<table id='myTable'>

<thead>

<tr><th>xxx</th><th>yyy</th></tr>

</thead>

<tbody>

</tbody>

</table>
How (in JavaScript) do I add a row of cells into the <tbody> section? I assumed that this:
document.getElementById('myTable').insertRow ( 0 )
...or perhaps this...
document.getElementById('myTable').insertRow ( 1 )
...would work - but they both add the new row into the <thead> section - I want to add to the <tbody> section.
If I manually add a garbage row into the HTML file for the <tbody>, then insertRow(2) happily adds my new row right after it in the <tbody> section...but I don't want a garbage entry at the top of my <tbody>!
I wondered whether I could find the <tbody> element and do an insertRow on the tbody - but the W3Schools docs suggest that you can only use insertRow on an actual <table> element.
Any clues?

 

Link to comment
Share on other sites

This is from the MDN reference:

If a table has multiple tbody elements, by default, the new row is inserted into the last tbody. To insert the row into a specific tbody:var specific_tbody=document.getElementById(tbody_id);var row=specific_tbody.insertRow(index)

 

I don't know if all browsers behave this way, you can test to make sure.

  • Like 1
Link to comment
Share on other sites

Many thanks!

 

Yeah - so it looks like the insertRow behavior for a table with a thead and an empty tbody isn't well-described...or at least not well-implemented.

 

It only really says what happens if you insert a row when there are multiple tbody elements (it puts the new row into the LAST tbody) - but it doesn't seem to mention what happens if there is a thead block present. It looks like both Chrome and Firefox behave as if the new element is added after the last row - no matter which section it's in. It's hard to say that this is a "bug" because the spec is unclear - but it is kinda unexpected, and definitely not the "nice" behavior I'd have expected!

 

Anyway, the MDN document does say that you can use insertRow on thead/tbody/tfoot elements - which ought to solve my problem.

 

Thanks for the link to that document!

 

-- Steve

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...