3

I have a problem and I have no idea how to solve it:

I have a table:


| A | B |

| D | C |

<table>
<tr>
<td>
A
</td>
<td>
B
</td>
</tr>
<tr>
<td>
C
</td>
<td>
D
</td>
</tr>
</table>

And now I need to add </tr><tr> after each odd td. Result should be one column table:


| A |

| B |

| C |

| D |

I was already trying to make this work with jQuery $("#table tr > td:nth-child(odd)").after("</tr><tr>");, but it doesn't work.

Can anyone advise?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Artjom
  • 37
  • 4
  • See http://stackoverflow.com/questions/171027/add-table-row-in-jquery By the way, the jQuery code isn't working since the table has no ID, but the jQuery code reffers to #table – Dennis Hunink Apr 07 '13 at 09:25
  • `` does not look like valid HTML which can be parsed to DOM. Keep in mind: jQuery works with DOM elements, not HTML. – Felix Kling Apr 07 '13 at 09:29
  • The reason I am doing it, I want this table to be responsive to screen width. So I want each cell to appear below previous when screen is less then ...px – Artjom Apr 07 '13 at 09:40
  • you can manipulate the `display` property of elements to achieve that. This way can avoid extensive and expensive DOM manipulation. – Ejaz Apr 07 '13 at 10:06
  • You mean I can `display:none` each even cell? This doesn't suit. If you mean something else, can you give me a hint? Brains are melting, so I am slow on understanding now :) – Artjom Apr 07 '13 at 10:11

2 Answers2

1

Try

$('table td:odd').each(function(i, v){
    var $this = $(this);
    var parent = $this.parent();
    $this.detach().wrap('<tr></tr>').insertAfter(parent)
})

Demo: fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Try this: (http://jsfiddle.net/b5S3U/4/)

var cols = 1;
$('tr').each(function () {
    var after = $(this);
    while ($(this).children().length > cols) {
        after = $('<tr>').insertAfter(after).append($('>:gt(' + (cols - 1) + '):lt(' + (cols) + ')', this));
    }
})
mrks
  • 8,033
  • 1
  • 33
  • 62