Programming/Javascript

Javascript 테이블 행의 값 가져오는 방법(table.rows / row.cells)

Jan92 2022. 10. 19. 22:24

javascript table 행의 값 가져오기

javascript에서 행의 값이 필요할 때 table.rows 함수와 row.cells 함수를 활용하여 값을 가지고 오는 코드입니다.

(rows collection, cells collection)

 

html 및 javascript 코드 중점으로 올리고 css의 경우 포스팅 맨 하단부에 추가해놓을 테니 필요하신 경우 참고 부탁드리겠습니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Table Row Event</title>
</head>
<body>
  <table id="eventTable">
    <thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Phone</th>
        <th>Email</th>
        <th>Date of Birth</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Susan</td>
        <td>Connor</td>
        <td>(02) 338-2765</td>
        <td>jmatman@gmail.com</td>
        <td>01/13/1979</td>
      </tr>
      
      ... (생략)
        
    </tbody>
  </table>
  
  <p></p>
</body>
</html>

(html 코드, 단순한 테이블 구조)

 

 

  <script>
    function rowClicked() {
      var table = document.getElementById('eventTable');
      var rowList = table.rows;

      for (i=1; i<rowList.length; i++) {
        var row = rowList[i];     //thead 부분을 제외하기 위해 i가 1부터 시작됩니다.
        var tdsNum = row.childElementCount;     //아래 for문에서 사용하기 위해 row 하위에 존재하는 td의 갯수를 구합니다.

        row.onclick = function() {
          return function() {
            var str = '';
            //row 안에 있는 값들을 순차적으로 가져오기
            for (var j=0; j<tdsNum; j++) {
              var row_value = this.cells[j].innerHTML;
              str += row_value + ' ';     //값을 하나의 문자열으로 만듭니다.
            };
            document.querySelector('p').innerText = str;     //p태그 안에 값을 넣어줍니다.
          };
        }(row);
      }
    }
    window.onload = rowClicked();
  </script>

(행의 값을 가져오는 javascript 코드)

 

table.rows 함수를 통해 rows collection을 가져올 수 있으며, row.cells 함수를 통해 cells collection을 가져올 수 있습니다.

(여기서는 row.cells[idx]를 통해 각 셀을 가져오고 있습니다.)

 

 

 

***

window.onload는 해당 함수 내의 스크립트 코드가 웹 브라우저 내의 모든 요소가 준비되고 난 후 실행될 수 있도록 하는 함수이며, 아래와 같이 함수를 오버라이딩 함으로써 사용할 수 있습니다.

<script>
window.onload = function() {
    var test = document.getElementById(’test’).innerHTML = 'hello world!';
}
</script>

 

<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
    $(document).ready(function(){
        var test = $( '#test' ).innerHTML = 'hello world';
      });
    }
</script>

(jquery를 사용했을 때)

 

$(function(){
  var test = $( '#test' ).innerHTML = 'hello world';
});

(한번 더 축약해서 사용)

 

 

 


  <style>
    body {
      padding: 1.5em;
      background: #f5f5f5;
    }
    table {
      border: 1px #a39485 solid;
      font-size: .9em;
      box-shadow: 0 2px 5px rgba(0,0,0,.25);
      width: 100%;
      border-collapse: collapse;
      border-radius: 5px;
      overflow: hidden;
    }
    th {
      text-align: left;
    }
    thead {
      font-weight: bold;
      color: #fff;
      background: #73685d;
    }
    td, th {
      padding: 1em .5em;
      vertical-align: middle;
    }
    td {
      border-bottom: 1px solid rgba(0,0,0,.1);
      background: #fff;
    }
    a {
      color: #73685d;
    }
  </style>

(테이블에 적용된 css 코드)

 

 

 

< 참고 자료 >

 

[ JavaScript ] 테이블 행 값 가져오기

안녕하세요! 오늘은 자바스크립트의 rows collection과 cells collection을 이용하여 클릭 된 행의 값을 가져와보겠습니다. 우선 자바스크립트 코드와 함께 사용할 html 과 css 코드를 작성해보겠습니다. ro

stickode.tistory.com