maxwell
maxwell

Reputation: 3

How to insert markup into a table using javascript

I have a table row with four cells. I'm trying to use javascript to insert this:

</tr><tr> 

in between two cells which would basically create two rows from one (at certain screen sizes).

I need to change this:

<table>
    <tr>
        <td>stuff</td>        
        <td>stuff</td>        
        <td>stuff</td>        
        <td>stuff</td>
    </tr>
</table>

into this:

<table>
    <tr>
        <td>stuff</td>        
        <td>stuff</td> 
    </tr><tr>       
        <td>stuff</td>        
        <td>stuff</td>
    </tr>
</table>

Here is my script:

$('table tr td:nth-child(3)').before('</tr><tr>');

And here is what I get:

<table>
    <tr>
        <td>stuff</td>        
        <td>stuff</td> 
    <tr></tr>            <--- notice that </tr><tr> becomes <tr></tr>!
        <td>stuff</td>        
        <td>stuff</td>
    </tr>
</table>

The tags are appearing in the right place, but they are switched around!

What the heck is going on here? Can anyone please help?

Upvotes: 0

Views: 79

Answers (2)

Bruno Calza
Bruno Calza

Reputation: 2780

You could add another row and transfer the last two td elements to the new row.

$('<tr>').insertAfter('tr').append($('td').slice(-2))

http://jsfiddle.net/g9xnsus5/2/

Upvotes: 0

Quentin
Quentin

Reputation: 943686

Despite the abstraction offered by jQuery, you are not working with HTML. You are working with DOM objects.

"</tr><tr>" gets interpreted as:

  1. End tag for table row which doesn't exist, ignore this
  2. Create a table row

You need to create a table row, put it where you want it to be and then move the table cells into it.

Possibly like this:

var tr = $('<tr />');
tr.append($('td+td+td'));
$('table').append(tr);

Upvotes: 1

Related Questions