Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle rowspan and colspan while converting "Table" into "Div"

I am converting table structured data into div using below code.

$('#content').html($('#content').html()
             .replace(/<tbody/gi, "<div id='table'")
             .replace(/<tr/gi, "<div style='overflow:auto;padding-top:15px;'")
             .replace(/<\/tr>/gi, "</div>")
             .replace(/<td/gi, "<span  style='float:left;margin-right:20px;'")
             .replace(/<\/td>/gi, "</span>")
             .replace(/<\/tbody/gi, "<\/div")); 

It works good mostly in all scenario except ROWSPAN & COLSPAN case.

How can I handle that design issue while converting Table into Div ? I am stuck in that.

like image 427
Priyank Avatar asked Jan 17 '23 03:01

Priyank


1 Answers

Maybe this gets you in the right direction:

.replace(/rowspan="/gi, 'class="rowspan-')
.replace(/colspan="/gi, 'class="colspan-')

Then make styles for the classes (e.g. rowspan-2 or colspan-3 etc.). However, this doesn't solve cases where one element has both row- and colspan, but it's a start.

A better way would be:

var copyAttr = function(old, $new) {
  for(var i = 0,
        attributes = old.attributes;
    i < attributes.length; i++) {

    $new.attr(attributes[i].name, attributes[i].value);
  }
  return $new;
}

$('#content').find('tbody').each(function() {
  var $new = copyAttr(this, $('<div id="table"></div>');
  $(this).replaceWith($new);
}).end().find('tr').each(function() {
  var $new = copyAttr(this, $('<div class="tr"></div>');
  $(this).replaceWith($new);
}).end().find('td').each(function() {
  var $new = copyAttr(this, $('<span class="td"></span>');
  $(this).replaceWith($new);
});

So now you have replaced the whole table structure with divs and spans with all the attributes the table elements had. Next you can change the row- and colspan attributes to classes.

$('#table .td').each(function() {
  var $t = $(this);
  $t
    .addClass('rowspan-'+$t.attr('rowspan'))
    .removeAttr('rowspan')
    .addClass('colspan-'+$t.attr('colspan'))
    .removeAttr('colspan');
});
like image 98
Simon Avatar answered Jan 31 '23 09:01

Simon