Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 tr 태그의 ID를 가져와 새 td 셀에 표시하는 방법

개요

HTML 테이블에서 각 <tr> 태그에 부여된 id 속성 값을 읽어와, 같은 행의 맨 앞에 새로운 <td> 셀을 추가하고 그 안에 ID를 표시하는 방법을 알아보겠습니다. 이 작업에는 document.querySelectorAll()insertCell() 메서드를 활용합니다.

먼저 예제로 사용할 테이블은 다음과 같습니다.

<table>
   <tr id='StudentDetails'>
      <th>StudentName</th>
      <th>StudentCountryName</th>
   </tr>
   <tr id='FirstRow'>
      <td>JohnDoe</td>
      <td>UK</td>
   </tr>
   <tr id='SecondRow'>
      <td>DavidMiller</td>
      <td>US</td>
   </tr>
</table>

위 테이블에는 세 개의 <tr> 태그가 있으며, 각각 StudentDetails, FirstRow, SecondRow라는 고유한 ID가 지정되어 있습니다.

구현 방법

tr 태그에서 ID를 가져와 새 td에 표시하려면 document.querySelectorAll('table tr')을 사용하여 테이블 내 모든 행을 선택한 뒤, 각 행에 대해 다음 작업을 수행합니다.

  • insertCell(0): 해당 행의 첫 번째 위치(index 0)에 새로운 셀을 삽입합니다.
  • textContent: 새로 만든 셀에 trObj.id, 즉 현재 행의 ID 값을 할당합니다.

전체 예제 코드

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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>
<style>
   td,
   th,
   table {
      border: 1px solid black;
      margin-left: 10px;
      margin-top: 10px;
   }
</style>
<body>
   <table>
      <tr id='StudentDetails'>
         <th>StudentName</th>
         <th>StudentCountryName</th>
      </tr>
      <tr id='FirstRow'>
         <td>JohnDoe</td>
         <td>UK</td>
      </tr>
      <tr id='SecondRow'>
         <td>DavidMiller</td>
         <td>US</td>
      </tr>
   </table>
</body>
<script>
   document.querySelectorAll('table tr').forEach(trObj => {
      var tableValue = trObj.insertCell(0);
      tableValue.textContent = trObj.id;
   });
</script>
</html>

코드 실행 방법

위 프로그램을 실행하려면 파일 이름을 “anyName.html(index.html)”로 저장합니다. 그다음 VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 “Open with Live Server” 옵션을 선택하면 브라우저에서 바로 결과를 확인할 수 있습니다.

실행 결과

프로그램을 실행하면 각 행의 맨 앞 열에 해당 행의 ID 값이 추가된 것을 확인할 수 있습니다. 즉, 헤더 행에는 StudentDetails, 두 번째 행에는 FirstRow, 세 번째 행에는 SecondRow가 새로운 td 셀로 삽입되어 화면에 표시됩니다.

JavaScript로 tr 태그의 ID를 가져와 새 td 셀에 표시하는 방법

핵심 정리

  • querySelectorAll('table tr')로 문서 내 모든 테이블 행을 NodeList 형태로 가져올 수 있습니다.
  • forEach()를 사용해 각 행을 순회하며 처리합니다.
  • insertCell(0)은 지정한 인덱스 위치에 새 셀을 삽입하며, 여기서는 항상 첫 번째 열에 추가됩니다.
  • textContent = trObj.id를 통해 DOM 객체에서 직접 id 속성 값을 읽어 셀에 출력합니다.