HOWTO · JavaScript

JavaScript를 사용하여 테이블 만들기

이 기사에서는 JavaScript를 사용하여 테이블을 만드는 방법을 살펴 봅니다.

이 페이지의 내용

JavaScript 데이터로 HTML 표를 만들려면 document.createElement()로 요소를 생성하고, textContent로 셀의 텍스트를 설정한 다음, 완성된 표를 appendChild()로 페이지의 컨테이너에 추가하면 됩니다. 페이지 실행 중 행 데이터가 바뀌는 경우에 유용한 방법입니다.

HTML 표의 구조와 필요한 요소

표는 중첩된 요소로 내용을 표현합니다. table 요소 안에는 행(tr)이 들어가고, 각 행에는 머리글 셀(th)이나 데이터 셀(td)이 들어갑니다. 행이나 열의 제목을 나타내는 셀에는 th를, 일반 데이터를 표시하는 셀에는 td를 사용합니다. 머리글 셀은 thead에만 사용할 수 있는 것이 아닙니다. 표 본문에서 행의 제목을 표시할 때도 사용할 수 있습니다.

thead와 tbody 요소는 각각 머리글 행과 본문 행을 묶습니다. 큰 표를 정리하기 쉽게 해 주지만, 모든 표에 반드시 필요한 것은 아닙니다. 필요하다면 tfoot으로 요약이나 바닥글 행을 묶을 수도 있습니다. 작은 표에서는 table과 그 안의 행 및 셀이 핵심 구조입니다. 그룹 요소는 구조를 더 명확하게 해 줄 때 추가하세요.

JavaScript로 표 만들고 채우기

아래 예제는 머리글 행 하나와 데이터 행 두 개를 만듭니다. 번호, 이름, 회사의 세 열로 표를 구성하고, 각 셀에는 textContent를 사용해 일반 텍스트를 넣습니다. 이 방식은 값을 HTML로 해석하지 않고 텍스트로 처리하므로, 사용자 입력이 포함될 수 있는 데이터를 다룰 때 더 안전한 기본 선택입니다.

아래 브라우저 예제는 브라우저의 기본 DOM API를 사용해 완성된 표를 기존 #table-container에 추가합니다. 이어지는 별도의 Node.js 데모는 간단한 DOM 형태의 모델로 행을 만드는 로직과 개수를 보여 줍니다. 이 데모는 브라우저 화면에 표를 표시하지 않습니다.

브라우저 페이지 예제(HTML 페이지로 저장한 뒤 브라우저에서 여세요):

이 섹션의 코드와 표시되는 레이블 또는 출력은 영어로 유지됩니다.

<!doctype html>
<html lang="en">
  <body>
    <div id="table-container"></div>
    <script>
      const container = document.getElementById("table-container");
      const table = document.createElement("table");
      const thead = document.createElement("thead");
      const tbody = document.createElement("tbody");
      const headings = ["No.", "Name", "Company"];
      const records = [
        ["1", "James Clerk", "Netflix"],
        ["2", "Adam White", "Microsoft"]
      ];

      const headerRow = document.createElement("tr");
      for (const heading of headings) {
        const cell = document.createElement("th");
        cell.textContent = heading;
        headerRow.appendChild(cell);
      }
      thead.appendChild(headerRow);

      for (const record of records) {
        const row = document.createElement("tr");
        for (const value of record) {
          const cell = document.createElement("td");
          cell.textContent = value;
          row.appendChild(cell);
        }
        tbody.appendChild(row);
      }

      table.appendChild(thead);
      table.appendChild(tbody);
      container.appendChild(table);
    </script>
  </body>
</html>

다음 독립 실행형 JavaScript 예제를 실행하세요:

class Element {
  constructor(name) {
    this.name = name;
    this.children = [];
    this.textContent = "";
  }

  appendChild(child) {
    this.children.push(child);
    return child;
  }
}

const document = {
  createElement(name) {
    return new Element(name);
  },
  body: new Element("body")
};

const container = document.createElement("div");
container.id = "table-container";
document.body.appendChild(container);

const table = document.createElement("table");
const thead = document.createElement("thead");
const tbody = document.createElement("tbody");
const headings = ["No.", "Name", "Company"];
const records = [
  ["1", "James Clerk", "Netflix"],
  ["2", "Adam White", "Microsoft"]
];

const headerRow = document.createElement("tr");
for (const heading of headings) {
  const cell = document.createElement("th");
  cell.textContent = heading;
  headerRow.appendChild(cell);
}
thead.appendChild(headerRow);

for (const record of records) {
  const row = document.createElement("tr");
  for (const value of record) {
    const cell = document.createElement("td");
    cell.textContent = value;
    row.appendChild(cell);
  }
  tbody.appendChild(row);
}

table.appendChild(thead);
table.appendChild(tbody);
container.appendChild(table);

const tableElement = container.children[0];
const headerCells = tableElement.children[0].children[0].children;
const bodyRows = tableElement.children[1].children;
console.log(`${headerCells.length} headings, ${bodyRows.length} data rows`);
3 headings, 2 data rows

document.createElement()는 문자열로 요소 이름을 받아 새 요소를 반환합니다. 코드에서는 각 행마다 tr을 만들고, 그 안에 th 또는 td 셀을 추가합니다. 각 셀을 채운 뒤 해당 행을 thead 또는 tbody에 넣습니다. 마지막으로 두 그룹을 표에 넣고, 처음에 만든 컨테이너에 표를 추가합니다.

직접 관리하는 페이지라면 컨테이너는 <div id="table-container"></div>처럼 간단하게 만들 수 있습니다. 브라우저 코드에서는 document.getElementById("table-container")로 기존 요소를 선택한 뒤 완성된 표를 추가하세요. 대상 요소가 이미 존재하도록 스크립트를 컨테이너 뒤에 배치하거나 문서 로드가 끝난 뒤 실행합니다. 표의 표현 방식은 CSS로 따로 지정할 수 있습니다. 예를 들어 table, th, td에 테두리와 여백을 적용할 수 있습니다. JavaScript는 구조와 내용을 만들고 CSS는 모양을 조절합니다.

표를 DOM에 추가하고 확인하기

완성된 표를 container.appendChild(table)로 선택한 컨테이너에 추가하세요. 이렇게 하면 표가 컨테이너 안에 들어가며 페이지의 나머지 부분은 그대로 유지됩니다. 기존 내용을 표로 바꾸려면 추가하기 전에 해당 내용을 명시적으로 지우세요. 그렇지 않으면 실행할 때마다 표가 하나씩 더 추가됩니다.

결과를 확인하려면 브라우저 개발자 도구를 열고 Elements 패널에서 컨테이너를 살펴보세요. 컨테이너 안에는 table이 있어야 하며, 그 안의 thead에는 th 셀 세 개가 있는 행 하나가, tbody에는 각각 td 셀 세 개가 있는 행 두 개가 있어야 합니다. 브라우저에 렌더링된 표에는 머리글 “No.”, “Name”, “Company”와 James Clerk / Netflix, Adam White / Microsoft가 표시되어야 합니다. 코드 예제의 머리글 레이블은 영어로 유지됩니다. 표가 보이지 않으면 컨테이너 ID와 스크립트 실행 시점을 확인하세요. 일반 텍스트 값에는 데이터를 innerHTML에 할당하지 말고 계속 textContent를 사용하세요.