1

Imagine a situation where I would like to put rows in a table dynamically:

<table>

  <tr><th>Title</th><th>Author</th>
  <div class="rowsGoHere"></div>

</table>

The problem with this code is that Chrome, for instance, considers <div> inside a <table> to be illegal, and the resulting page code I see in inspector is the following:

<div class="rowsGoHere"></div>
<table>
  <tr><th>Title</th><th>Author</th>
</table>

So Chrome automatically puts this div above the table. Now the question is, how do I avoid this situation? Is it possible to use something other than this <div> which I can later reference to insert elements into or after it? I should also point out the requirement that this element should be generic: I can't just use <tr class="rowsGoHere">.

This is a strictly html validity question, please do not recommend any jQuery code or something similar.

orion3
  • 9,797
  • 14
  • 67
  • 93

2 Answers2

1

You can always use tbody to append the new rows

<table>
   <thead>
   <tr><th>Title</th><th>Author</th>
   </thead>
   <tbody>
   <!--rowsGoHere-->
   </tbody>
</table>
Kostis
  • 1,105
  • 8
  • 10
  • This wouldn't work, as I pointed out - it should be a generic element (it's a requirement). But your answer gave me an idea: can I use a comment ``? Is it a recognizable DOM member? Can I insert after or before it? – orion3 Jan 04 '14 at 23:47
  • What do you mean by 'generic element'? Instead of
    you can have
    – Kostis Jan 04 '14 at 23:50
  • What I mean is: I need one element that I can use both inside and outside the `` tag.
    – orion3 Jan 04 '14 at 23:51
  • Oh i see. That's gonna be tricky then. Your idea of using the HTML comment to append/prepend rows could work. This might help http://stackoverflow.com/questions/18578784/insert-html-block-after-a-specific-html-comment – Kostis Jan 04 '14 at 23:58
  • Yeah, I've tested it. It actually works. Thanks for helping me find this out. – orion3 Jan 05 '14 at 00:03
1

So I ended up doing this:

<table>

  <tr><th>Title</th><th>Author</th>
  <!--rowsGoHere-->

</table>

I could then identify this comment as a DOM element and insert what I need before it with insertBefore(). This approach has the advantage of being completely valid no matter which html elements it is used with (I can use it both with <table> as well as within <div> or <ul>).

orion3
  • 9,797
  • 14
  • 67
  • 93