let _a = a.children[col].textContent; 辺りの部分でエラーが出ます。

2020年4月19日
ユーザー

1時間ほど、"自分のコードと比較"機能を使って間違いを探しているのですが何回見ても全部あっているようにしかみえず、エラーの原因がわかりません。

お手本のコードをコピペして動かしてみたら正常に動いたのでjsファイルのどこかに文法的におかしい部分があるのだと思われますが原因がどうしてもわかりません。

以下のようなエラーが出ました。

tablesort.js:14 Uncaught TypeError: Cannot read property 'textContent' of undefined
    at tablesort.js:14
    at Array.sort (<anonymous>)
    at HTMLTableCellElement.<anonymous> (tablesort.js:13)

以下私が書いたコードです。

"use strict";
{
  let ths = document.getElementsByTagName("th");
  let i;

  for (i = 0; i < ths.length; i++) {
    ths[i].addEventListener("click", () => {
      let rows = Array.prototype.slice.call(
        document.querySelectorAll("tbody > tr")
      );
      let col = this.cellIndex;

      rows.sort(function (a, b) { //ここが14行目です。
        let _a = a.children[col].textContent; 
        let _b = b.children[col].textContent;
        if (_a < _b) {
          return -1;
        }
        if (_a > _b) {
          return 1;
        }
        return 0;
      });

      const tbody = document.querySelector(tbody);

      while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
      }

      let j = 0;
      for (j = 0; j < rows.length; j++) {
        tbody.appendChild(rows[j]);
      }
    });
  }
}

お手数おかけしますが、ご教授いただければ幸いです。

この回答を見るにはプレミアムプランへの登録が必要です

プレミアムプランとは?