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>)는, 어느 행에 있어도 무시합니다.이것이 바로 이 방법입니다.
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
})
})
해라
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
let val = cell.innerText; // your code below
}
}
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
console.log(cell.innerText)
}
}
<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>
for ( let [i,row] of [...mytab1.rows].entries() )
{
for( let [j,cell] of [...row.cells].entries() )
{
console.log(`[${i},${j}] = ${cell.innerText}`)
}
}
<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>
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가 할당되어 루프가 정지(종료)되는 동안 반복됩니다.
더 나은 솔루션: 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.rowIndex그리고.cell.colIndex사용하는 대신row_ind그리고.col_ind.
이 접근방식은 글로벌 변수와 함께 코드를 혼란시키지 않기 때문에 가장 높은 투표율을 보이는 답변 2개보다 훨씬 선호합니다.i,j,row그리고.col따라서 부작용(또는 보풀/컴파일러 경고 발생)이 없는 깨끗한 모듈러 코드를 제공합니다.다른 라이브러리 없음(예: jquery).
이전 버전(ES2015 이전)의 Javascript에서 실행하도록 요구하는 경우,Array.from폴리필이 가능합니다.
다음과 같은 기능적인 스타일을 원하는 경우:
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#의 확장 메서드와 유사한 방법으로 사용 가능)를 수정하여 컬렉션을 배열로 변환하는 함수를 포함시킴으로써 위의 스타일(C#의 linq 스타일)의 상위 함수를 사용할 수 있습니다.
Object.defineProperty(HTMLCollection.prototype, "toArray", {
value: function toArray() {
return Array.prototype.slice.call(this, 0);
},
writable: true,
configurable: true
});
이 솔루션은 나에게 완벽하게 작용했다.
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 = "";
}
}
를 사용하여 모든 것을 선택할 수 있습니다.td를 사용하여 이들 요소를 루프합니다.이러한 값은 다음과 같이 취득할 수 있습니다.
const cells = document.querySelectorAll('td');
cells.forEach(function(cell) {
console.log(cell.innerHTML);
})
<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>
특정 행에서 열만 선택하려면 의사 클래스를 사용하여 특정 행을 선택할 수 있습니다.tr(옵션으로 자 조합()>과 함께 사용할 수 있습니다)(테이블 내에 테이블이 있는 경우 유용합니다).
const cells = document.querySelectorAll('tr:nth-child(2) > td');
cells.forEach(function(cell) {
console.log(cell.innerHTML);
})
<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>
루프에 단일 사용:
var table = document.getElementById('tableID');
var count = table.rows.length;
for(var i=0; i<count; i++) {
console.log(table.rows[i]);
}
es6를 사용한 솔루션:
var table = document.getElementById('mytab1');
var data = [...table.rows].map(row => [...row.cells].map(td => td.innerText));
console.log(data)
자료: 고 re re re:
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLCollectionhttpsdeveloper.mozilla.org/pt-BR/docs/Web/API/
다음은 최신 Javascript ES6+를 사용하는 한 가지 솔루션입니다.
const rows = document.querySelector("table")?.rows;
if (!rows) {
return;
}
Array.from(rows).forEach(row => {
console.log(row);
const cells = Array.from(row.cells);
cells.forEach(cell => {
console.log(cell);
});
});
Array.from()HTML Collection은 Javascript를 사용합니다.
『 』의 매뉴얼:table.rows사용방법 : https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows
『 』의 매뉴얼:row.cells사용방법 : https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement
은 '하다'를 방법입니다.childNodes ★★★★★★★★★★★★★★★★★」HTMLCollection
<script>
var tab = document.getElementsByTagName("table")
for (var val of tab[0].childNodes[1].childNodes.values())
if (HTMLCollection.prototype.isPrototypeOf(val.children)) {
for (var i of val.children) {
console.log(i.childNodes[0])
}
}
</script>
특정 HTML 테이블 컬럼을 스크랩하여 결과를 인쇄하기 위해 나중에 참고하기 위해 남겨둡니다.
//select what table you want to scrape (is zero based)
//set 0 if there is only one
setTable=0;
//select what column you want to scrape (is zero based)
//in this case I would be scrapping column 2
setColumnToScrape=1;
var table = document.getElementsByTagName("tbody")[setTable];
for (var i = 0, row; row = table.rows[i]; i++) {
col = row.cells[setColumnToScrape];
document.write(col.innerHTML + "<br>");
}
순수 자바스크립트
function numberofRow(){
var x = document.getElementById("mytab1").rows.length;
document.getElementById("mytab1").innerHTML = x;
}
numberofRow();
<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>
es6:
const table = document.getElementById('some-table');
const cells = table.getElementsByTagName('td');
for (let cell of cells) {
// do something with cell here
}
이전 버전:
var table = document.getElementById('some-table');
var cells = table.getElementsByTagName('td');
for ( var i in cells ) {
// do something with cells[i]
}
출처 : https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
언급URL : https://stackoverflow.com/questions/3065342/how-do-i-iterate-through-table-rows-and-cells-in-javascript
'source' 카테고리의 다른 글
| Python 소스 코드에서 UML 다이어그램을 생성하는 가장 좋은 방법은 무엇입니까? (0) | 2023.01.06 |
|---|---|
| 모듈 경로를 검색하는 방법 (0) | 2023.01.06 |
| MySQL 인덱스 - 모범 사례는 무엇입니까? (0) | 2023.01.06 |
| PHP에서 HTML/XML을 어떻게 해석하고 처리합니까? (0) | 2023.01.06 |
| MYSQL의 LIMIT 값이 클수록 쿼리가 느려지는 이유는 무엇입니까? (0) | 2023.01.06 |