开发者

how to remove and re-order cells in a table in JavaScript

As per question how could I remove empty cells and bring cells with data on top of the table in JavaScript/Prototype, basically all cells with data will be at the top and then empty cells should be removed.

<table>
    <tr class="row">
        <td class="c1">Cell1</td>
        <td class="c2">Cell2</td>
    </tr>
    <tr class="row">
        <td class="c1">Cell1</td>
        &l开发者_StackOverflow社区t;td class="c2"></td>
        <td class="c3">Cell3</td>
    </tr>
    <tr class="row">
        <td class="c1">Cell1</td>
        <td class="c2">Cell2</td>
        <td class="c3"></td>
    </tr>
</table>


Cell1   Cell2                    Cell1  Cell2   Cell3
Cell1           Cell3     --->   Cell1  Cell2
Cell1   Cell2                    Cell1

Thanks


In the end it's a little bit of an algorithm that needs to be coded.

I simply used DOM-functionality as I'm not that familiar with jQuery or other frameworks, but I think you can figure out the idea of the algorithm. It shouldn't be too hard to convert it.

<html>
<head>
<script type="text/javascript">
function init() {
  var table = document.getElementsByTagName("table")[0];
  var trs = table.getElementsByTagName("tr");
  var data = [];
  var rows, columns;

  // run through all TRs and TDs and collect the data into an array without
  // empty slots
  for (var r = 0; r < trs.length; r++) {
    var tds = trs[r].getElementsByTagName("td");

    for (var d = 0; d < tds.length; d++) {
      if (tds[d].innerHTML) {
        data[d] = (data[d] || []).concat(tds[d].innerHTML);
      }
    }
  }

  // the tricky thing now is to convert the X/Y alignment of the
  // elements in data into a Y/X one for the table

  columns = data.length;        // target table will have this many columns
  rows = data[0].length;        // target table will have this many rows

  table = document.createElement("table");

  for (var r = 0; r < rows; r++) {
    var tr = document.createElement("tr");

    for (var c = 0; c < columns; c++) {
      var td = document.createElement("td");

      td.innerHTML = data[c][r] || "";
      tr.appendChild(td);
    }

    table.appendChild(tr);
  }
  document.body.appendChild(table);
}
</script>
</head>
<body onload="init()">
<table>
    <tr class="row">
        <td class="c1">Cell1</td>
        <td class="c2">Cell2</td>
    </tr>
    <tr class="row">
        <td class="c1">Cell1</td>
        <td class="c2"></td>
        <td class="c3">Cell3</td>
    </tr>
    <tr class="row">
        <td class="c1">Cell1</td>
        <td class="c2">Cell2</td>
        <td class="c3"></td>
    </tr>
</table>
</body>
</html>

The output matches your request.


window.onload = function() {
    var tds = document.getElementsByTagName("td");
    for(var i=0; i<tds.length; i++) {
        if(tds[i].innerHTML == "") {
            tds[i].parentNode.removeChild(tds[i]);
        }
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜