Trigun Trigun - 6 months ago 15
Javascript Question

jquery/css get elements in a table ordered in column instead rows

I have a list of elements like this

1
2
3 6
4 7
5 8
9
10


all the numbers are links .. if I use
$("a")
i get the order


(1,2,3,6,4,7,5,8,9,10)


there is a easy way for scan the table by column? or I need to transpose all the tables before the
$("a")
(i think isn't the best way)

i need to open all the links with ajax something like that

method: 'GET',
url: ARRAY,
accept: 'text/xml',
onreadystatechange: function (indexValue,css,css2,css3,urlFrom) {
return function (response) {
if (response.readyState != 4)
return;
chap = $(response.responseText).find(css)[0].innerHTML + (css.indexOf(",") != -1 ? $(response.responseText).find(css)[1].innerHTML : "");
$("#page-"+(indexValue))[0].innerHTML = chap;
$("#page-"+(indexValue)).find(css2).remove();
if (css3 != "")
$("#page-"+(indexValue)).find(css3).eq(0).prevAll().remove();
}
}(i,classCss,remCss,remblabla,location.href.replace("https://","http://")),


if I don't get the right order the order of the pages get scrambled so is a mess :-(

Answer

Here is an example at column-major instead of row-major. The script reads a table in reverse-order and adds elements to a 2-dimensionnal array.

var maxColumn = 0;
var invert = [];

$("#yourTable tr").each(function() {
  $(this).find("td").each(function(index) {
    if (index + 1 > maxColumn) maxColumn = index + 1;
  });
});

for (var i = 0; i < maxColumn; i++) {
  for (var j = 0; j < $("#yourTable tr").size(); j++) {
    if ($("#yourTable tr").eq(j).find("td").eq(i).html() !== undefined) {
      if (invert[i] === undefined) invert[i] = [];
      invert[i][j] = $("#yourTable tr").eq(j).find("td").eq(i);
    }
  }
}

document.write("<p>Above gives : </p>");

for (var k = 0; k < invert.length; k++) {
  document.write("<br/>");
  for (var l = 0; l < invert[k].length; l++) {
    if (invert[k][l] !== undefined) {

      // You have a jQuery collection so to access the link :
      var link = invert[k][l].find("a").eq(0).attr("href");
      document.write(link + " - ");
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="yourTable">
  <tr>
    <td><a href="link 5">5</a></td>
    <td><a href="link 6">6</a></td>
    <td><a href="link 7">7</a></td>
  </tr>
  <tr>
    <td><a href="link 1">1</a></td>
    <td><a href="link 2">2</a></td>
    <td><a href="link 3">3</a></td>
    <td><a href="link 4">4</a></td>
  </tr>
  <tr>
    <td><a href="link 8">8</a></td>
    <td><a href="link 9">9</a></td>
  </tr>
  <tr>
    <td><a href="link 10">10</a></td>
  </tr>
</table>

Comments