Organizing Table Data

Quick one today, I just wanted to add a cute little function that quickly traverses a table and organizes an array of html dom elements by table head tag (th).

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

NodeList.prototype.toArray = function() {
  return Array.prototype.slice.call(this);
};

function CollectData(className) {
  var table = document.querySelector(className);
  var thead = table.querySelector('thead');
  var tbody = table.querySelector('tbody');
  var ths = thead.querySelectorAll('th').toArray();
  var trs = tbody.querySelectorAll('tr').toArray();
  
  return ths.map(function(th, idx) {
    return trs.map(function(tr) {
      return tr.querySelectorAll('td')[idx];
    });
  });
}

[/pastacode]

It basically, manually walks the table, then returns an array based on what it finds in the table headers. The Nodelist function at the top just adds a “toArray()” function to the nodelist object so you can get output from querySelector as an array.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.