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).

NodeList.prototype.toArray = function() {

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, idx) {
    return {
      return tr.querySelectorAll('td')[idx];

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 *