0

I have a standard table:

I want to use jQuery to reformat the table, more specifically I want to add a closing tr and open a new tr within the tbody for the first td..

I can target it ok with the below jquery and the html is inserted but in the wrong way..

$('</tr><tr>').insertAfter('.table thead tr td:first-child');

the new markup is in the wrong order ... any help would be appreciated.

<tr></tr> <--wrong!

I need it to be:

</tr><tr>

am I missing something?

<table>
    <thead>
        <tr>
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
           <td>5</td>
           <td>6</td>
        </tr>
    </thead>
    <tbody>
        <tr>
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
           <td>5</td>
           <td>6</td>
        </tr>
        <tr>
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
           <td>5</td>
           <td>6</td>
        </tr>
        <tr>
           <td>1</td>
           <td>2</td>
           <td>3</td>
           <td>4</td>
           <td>5</td>
           <td>6</td>
        </tr>
    </tbody>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Iamsamstimpson
  • 1,359
  • 2
  • 17
  • 32

2 Answers2

1

jQuery, and JavaScript in general creates and manipulates valid DOM elements/nodes; it doesn't insert strings into the HTML (although you could do that with the .html()/innerHTML methods, albeit with some potential parsing difficulties). If you want to insert a new row into the thead, then simply:

$('<tr />').insertAfter('thead tr:last');

I'm not sure why you're trying to insert a string rather than a new node/element. If you update your question with more specific information as to what you're trying to do I'll update my answer with a better solution (if possible).

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • I'm reformatting a table when the screen/window size goes below 480px - so a mobile has the same table but formatted better for the screen.. I'm having problems converting huge tables to fit within smaller screen areas. – Iamsamstimpson Jun 12 '12 at 13:15
0

You are converting the tr into jquery dom element. which can not let you do this. it always maintain the opening and closing order of the tag.

You have to do String manipulation by getting the HTML of the first Tr of the table

var html = ('.table thead tr:first-child').html();
Zahid Riaz
  • 2,879
  • 3
  • 27
  • 38
  • var html = ('.table thead tr:first-child').html(); html = html.replace(//, ""); ('.table thead tr:first-child').html(html); – Zahid Riaz Jun 12 '12 at 11:35