BLane
BLane

Reputation: 1

Using JQuery .append() to dynamically change table layout

I am using an HTML table but I want to dynamically change the layout of the table based on the browser size. My basic code looks like this:

<tr>
  <td class="row">E1</td>
  <td class="row">E2</td>
  <td class="row">E3</td>
  <td class="lastRow">E4</td>
</tr>

Then the JQuery should calculate the number of rows and insert row-breaks accordingly. My JQuery looks like this for now:

$('td.row').append('</tr><tr>');

Yet, its still displaying all the elements on one line. Any idea why?

Upvotes: 0

Views: 258

Answers (6)

user113716
user113716

Reputation: 322502

You need to not think in terms of constructing HTML markup. There's no way to splice a closing/opening </tr><tr> into the DOM (without some ugly .innerHTML hacks).

Instead, create a new row after the current row, and the relocate the cells into that new row.

var row_cells = $('td.row').slice(1);

row_cells.each( function( i, el ) {
    $('<tr>').insertAfter( row_cells.eq(i).parent() )
             .append( row_cells.eq(i) );
});

DEMO: http://jsfiddle.net/EDf5a/


Or maybe you wanted a new row for each cell:

var row_cells = $('td.row');
var row = row_cells.parent();

row_cells.each(function(i, el) {
    $('<tr>').insertBefore(row)
        .append(row_cells.eq(i));
});

DEMO: http://jsfiddle.net/EDf5a/1/

Upvotes: 0

Andrew Church
Andrew Church

Reputation: 1391

You'd want to do your append on the tr element, not on td.row

Upvotes: 0

v42
v42

Reputation: 1425

$('</tr><tr>').insertAfter('.row');

Upvotes: 0

Jorge
Jorge

Reputation: 18247

i think that you need to try with this selector

Asumming that your table haved an id called example try like this

$("#exmaple tr:last").append('<tr></tr>');

Upvotes: 0

RSG
RSG

Reputation: 7123

This is a perfect place to use fluid CSS layouts.

Instead of writing lots of crazy Dom-manipulating javascript, simply replace your TD tags with divs and have them float:left

Further- append does not do what you think it does. It's dom manipulation and not string manipulation- you can't use it to directly change HTML the way you're thinking.

Further reading

Upvotes: 1

jeffreydev
jeffreydev

Reputation: 1722

Try looking at .after(); function:

http://api.jquery.com/after

Upvotes: 0

Related Questions