HTML 테이블에 담긴 데이터를 JavaScript에서 다루려면 배열 형태로 변환하는 것이 편리합니다. jQuery의 find() 메서드를 사용해 태그에서 데이터를 가져오고, push() 메서드를 사용해 해당 데이터를 배열에 저장할 수 있습니다.
예제 테이블
다음과 같은 테이블이 있다고 가정해 보겠습니다.
<table id="details">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr><td>John</td><td>23</td>
<tr><td>David</td><td>26</td>
</tbody>
</table>
테이블 데이터를 배열로 변환하기
<td> 태그의 데이터를 가져와 배열에 저장해 보겠습니다. 다음은 전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.notShown {
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<table id="details">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr><td>John</td><td>23</td>
<tr><td>David</td><td>26</td>
</tbody>
</table>
<script>
var convertedIntoArray = [];
$("table#details tr").each(function() {
var rowDataArray = [];
var actualData = $(this).find('td');
if (actualData.length > 0) {
actualData.each(function() {
rowDataArray.push($(this).text());
});
convertedIntoArray.push(rowDataArray);
}
});
console.log(convertedIntoArray);
</script>
</body>
</html>
코드 동작 원리
- $("table#details tr") : id가 details인 테이블의 모든 행(tr)을 선택합니다.
- each() : 선택된 각 행을 순회하며 처리합니다.
- find('td') : 현재 행에서 td 셀만 찾아냅니다. th 헤더 셀은 자동으로 제외됩니다.
- push($(this).text()) : 각 셀의 텍스트 내용을 rowDataArray에 순서대로 추가합니다.
- convertedIntoArray.push(rowDataArray) : 한 행이 완성되면 이를 최종 2차원 배열에 저장합니다.
실행 방법
위 프로그램을 실행하려면 파일 이름을 "anyName.html(index.html)"로 저장한 뒤, 해당 파일을 마우스 오른쪽 버튼으로 클릭하세요. VS Code 편집기에서 "Open with Live Server" 옵션을 선택하면 브라우저에서 바로 실행할 수 있습니다.
출력 결과
위 코드를 실행하면 개발자 도구 콘솔에 다음과 같은 2차원 배열이 출력됩니다.
[["John", "23"], ["David", "26"]]
