[JS] 테이블 동적으로 삽입 생성하기

전예원·2021년 10월 25일
0

Java Script 공부

목록 보기
24/33

💡 JS로 테이블의 row와 column을 동적으로 삽입하는 방법을 공부해보자!

⭐️ 완성샷


🔴 html, css


🟠 JS


  • window.onload 함수 안에 작성
  • 버튼 변수에 저장해주기
  • 버튼 클릭시~~ 에 작성
  • tbody 변수에 저장 (난 tbody에 id=htmlTboddy를 줬음)
    const hTbody = document.getElementById('htmlTbody');

🟡 Js Table Row And Column


🟤 insert a row at the end of table

  • 줄 삽입하기
  • 즉, tr을 삽입하는 것
const newRow0 = hTbody.insertRow(); 
  • 테이블.insertRow();를 사용해서 tbody에 테이블 요소를 추가해준다.
  • 통짜로 된 row 한 줄이 추가된다.

🟤 insert a cell at the end of the row

  • cell 삽입하기
  • 즉, td를 삽입하는 것
const newCell0 = newRow0.insertCell();
const newCell1 = newRow0.insertCell();
const newCell2 = newRow0.insertCell();
const newCell3 = newRow0.insertCell();
  • 생성된row.insertCell();를 사용 할 때마다 td가 한개씩 삽입됨
  • 생성된 row에 셀을 삽입한다!

🟤 Append - 텍스트 노드를 새롭게 생성한 Cell에 붙이기

  • 셀에 값을 입력하기
const newText0 = document.createTextNode('홍길동');
newCell0.appendChild(newText0);
const newText1 = document.createTextNode('hong@abc.com');
newCell1.appendChild(newText1);
const newText2 = document.createTextNode('25살');
newCell2.appendChild(newText2);
const newText3 = document.createTextNode('영화보기');
newCell3.appendChild(newText3);
  • 생성된 셀에 텍스트 노드를 입력한다.
  • .createTextNode('내가 입력하고 싶은 값')
  • 생성된cell.appendChild(텍스트값)

🟤 테이블 row 개수 구하기

const table = document.getElementById('myTable'); // 전체 테이블에 id값을 줌

console.log(table.rows.length-1); // -1은 thead 빼고, 계산하기 위해서
console.log(table.rows[0]); // thead 영역 출력 
console.log(table.rows[1]); // tbody -> first row

// table의 tbody의 개수를 변수에 저장
const r = table.rows.length - 1; // -1은 table로 부터 가져와서 thead까지 계산함

  • 테이블의 행의 개수는 thead까지 계산을 한다. tbody의 개수만 알고 싶으면 -1해야한다.

🟤 셀(Cell)이 몇개인지를 알고 싶다면??

// 해당 row의 cell이 몇개인지를 출력함
const l = table.rows[r].cells.length;
console.log(table.rows[r].cells.length);
  • row[n].cells의 길이를 구하면된다.

🟤 반복문 순회하면서 각 Cell에 정보 값을 셋팅

for(let c = 0; c<l; c++) {
   hTbody.rows[r-1].cells[c].innerHTML = `[${r-1}][${c}]`
}
  • hTbody기준이라서 table기준으로 r의 개수를 설정해놔서 -1을 해줘야한다.
profile
앞으로 나아가는 중~

0개의 댓글