Reputation: 3
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
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
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:
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