Search code examples
jqueryhtmlhtml-tablemarkupinsertafter

Jquery: table markup manipulation using .insertAfter


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>

Solution

  • 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).