테이블의 열과 줄을 동적으로 생성

zzincode·2023년 1월 12일
0

JavaScript

목록 보기
5/24
post-thumbnail

📍Table Cell 만들기

//Insert a row
const newRow0 = hTbody.insertRow();

//Insert a cell
const newCell0 = newRow0. insertCell();
const newCell1 = newRow0. insertCell();
const newCell2 = newRow0. insertCell();
const newCell3 = newRow0. insertCell();

결과

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

 const newText0 = document.createTextNode("[0][0]");
 newCell0.appendChild(newText0);

 const newText1 = document.createTextNode("[0][1]");
 newCell1.appendChild(newText1);

 const newText2 = document.createTextNode("[0][2]");
 newCell2.appendChild(newText2);

 const newText3 = document.createTextNode("[0][3]");
 newCell3.appendChild(newText3);


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

 window.onload = () => {
  const btnCreate = document.querySelector(".btnCreate");

  btnCreate.addEventListener("click", () => {
    let hTbody = document.getElementById("htmlTbody");

    const newRow0 = hTbody.insertRow();
    
    const newCell0 = newRow0.insertCell();
    const newCell1 = newRow0.insertCell();
    const newCell2 = newRow0.insertCell();
    const newCell3 = newRow0.insertCell();

    
    const table = document.getElementById("myTable");
   
    const r = table.rows.length - 1;
    const l = table.rows[r].cells.length;
    

    for (let c = 0; c < l; c++) {
      hTbody.rows[r - 1].cells[c].innerHTML = `[${r - 1}][${c}]`;
    }
  });
};

버튼 클릭할 때마다 테이블 추가

0개의 댓글