반복문으로 출력되는 목록형태의 데이터(e.g. table > tr, ul > li)의 row 갯수를 출력해야 하는 경우가 있다. Document 의 렌더링이 모두 끝난 후 이를 출력해야 하는 경우가 있는데 이럴 때 DOMContentLoaded 이벤트를 사용할 수 있다.
- DOMContentLoaded 는 DOM Tree 가 완전히 다 만들어지면 접근하여 이벤트 발생
<table id="article">
<thead>
<tr>
<th>No</th>
<th>Subject</th>
<th>Author</th>
</tr>
</thead>
<tbody>
loop ...
</tbody>
<tfoot>
<tr>
<td colspn="3" id="rowCount"></td>
</tr>
</tfoot>
</table>
document.addEventListenr("DOMContentLoaded", function() {
const table = document.getElenentById("article");
const tbody = table.querySelector("tbody");
const updateRows = () => {
const rowCount = tbody.getElementsByTagName("tr").length;
// class 등의 selector 를 사용 시. tag 를 특정하는 것보다는 출력이 느리다.
// const rowCount = tbody.querySelectorAll(".row").length;
const rowCountCell = ducumnet.getElementById("rowCount");
rowCountCell.textContent = `Total: ${rowCount}`
};
// 페이지 로드 시와 행이 추가/삭제될 때마다 업데이트
updateRows();
// table.addEventListener("DOMSubtreeModified", updateRowCount);
});