[javascript] JavaScript에서 테이블 행과 셀을 어떻게 반복합니까?

HTML 테이블이 있다면 …

<div id="myTabDiv">
<table name="mytab" id="mytab1">
  <tr>
    <td>col1 Val1</td>
    <td>col2 Val2</td>
  </tr>
  <tr>
    <td>col1 Val3</td>
    <td>col2 Val4</td>
  </tr>
</table>
</div>

모든 테이블 행을 반복하고 (확인 할 때마다 행 수가 변경 될 수 있다고 가정) JavaScript 내에서 각 행의 각 셀에서 값을 검색하는 방법은 무엇입니까?



답변

각 행 ( <tr>)을 통해 행을 알고 / 확인하고 <tr>( <td>) 각 행 ( <tr>) 의 각 열 ( )을 반복 하려면이 방법을 사용하십시오.

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }
}

<td>어떤 행을 무시하고 cells ( ) 을 살펴보고 싶다면 이 방법입니다.

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
     //iterate through cells
     //cells would be accessed using the "cell" variable assigned in the for loop
}


답변

jQuery 사용을 고려할 수 있습니다. jQuery를 사용하면 매우 쉽고 다음과 같이 보일 수 있습니다.

$('#mytab1 tr').each(function(){
    $(this).find('td').each(function(){
        //do your stuff, you can use $(this) to get current cell
    })
})


답변

var table=document.getElementById("mytab1");
var r=0; //start counting rows in table
while(row=table.rows[r++])
{
  var c=0; //start counting columns in row
  while(cell=row.cells[c++])
  {
    cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell
  }
}
<table id="mytab1">
  <tr>
    <td>A1</td><td>A2</td><td>A3</td>
  </tr>
  <tr>
    <td>B1</td><td>B2</td><td>B3</td>
  </tr>
  <tr>
    <td>C1</td><td>C2</td><td>C3</td>
  </tr>
</table>

각 패스 스루 동안 루프 r / c 반복자가 증가하고 콜렉션의 새 행 / 셀 오브젝트가 행 / 셀 변수에 지정됩니다. 콜렉션에 행 / 셀이 더 이상 없으면 행 / 셀 변수에 false가 지정되고 while 루프 중지 (종료)를 통해 반복됩니다.


답변

시험

for (let row of mytab1.rows)
{
    for(let cell of row.cells)
    {
       let val = cell.innerText; // your code below
    }
}


답변

이 솔루션은 나를 위해 완벽하게 작동했습니다.

var table = document.getElementById("myTable").rows;
var y;
for(i = 0; i < # of rows; i++)
{    for(j = 0; j < # of columns; j++)
     {
         y = table[i].cells;
         //do something with cells in a row
         y[j].innerHTML = "";
     }
}


답변

다음과 같이 기능적인 스타일을 원하는 경우 :

    const table = document.getElementById("mytab1");
    const cells = table.rows.toArray()
                  .flatMap(row => row.cells.toArray())
                  .map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]

HTMLCollection의 프로토 타입 객체를 수정하고 (C #의 확장 메서드와 유사한 방식으로 사용 가능) 컬렉션을 배열로 변환하는 함수에 포함하여 위 스타일 (in linq 스타일의 종류)에서 고차 함수를 사용할 수 있습니다. 씨#):

    Object.defineProperty(HTMLCollection.prototype, "toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });


답변

더 나은 솔루션 : Javascript의 네이티브를 사용 Array.from()하고 HTMLCollection 객체를 배열로 변환 한 후 표준 배열 함수를 사용할 수 있습니다.

var t = document.getElementById('mytab1');
if(t) {
    Array.from(t.rows).forEach((tr, row_ind) => {
        Array.from(tr.cells).forEach((cell, col_ind) => {
            console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
        });
    });
}

또한 참조 할 수 tr.rowIndexcell.colIndex대신 사용 row_ind하고 col_ind.

나는 많이 전역 변수와 코드를 복잡하게하지 않기 때문에 (2)는 답변을 가장 높은 투표 맨 위에이 방법을 선호 i, j, rowcol, 따라서 그것은 깨끗하고 모듈 부작용이 없습니다 코드 제공 (또는 인상 보풀 / 컴파일러 경고) … 다른 라이브러리가없는 경우 (예 : jquery)

이전 버전 (ES2015 이전)의 자바 스크립트에서 실행 Array.from해야하는 경우 폴리 필 할 수 있습니다.