JavaScript / childElementCount로 자식 요소 개수 구하기

element.childElementCount는 요소의 바로 아래에 있는 자식 요소 수를 반환하는 읽기 전용 속성입니다. 텍스트나 주석 노드는 세지 않으며, 자식 안에 더 깊이 중첩된 요소도 직접 자식이 아니면 포함하지 않습니다. 자식을 추가하거나 삭제한 뒤 다시 읽으면 현재 개수를 얻습니다.

직접 자식 요소만 세기

아래 ul에는 직접 자식 li가 두 개 있습니다. 첫 번째 li 안의 strong은 손자 요소이므로 ul.childElementCount에 포함되지 않습니다. children.length도 직접 자식 요소 수를 나타냅니다.

const list = document.querySelector('#items');
console.log(list.childElementCount); // 2
console.log(list.children.length); // 2

childNodes.length와는 다릅니다. childNodes에는 HTML의 줄바꿈이나 공백으로 생긴 텍스트 노드, 주석 노드도 들어갈 수 있어 들여쓰기 방식에 따라 값이 달라집니다. MDN의 childElementCount 문서와 childNodes 문서를 비교하세요.

자식이 바뀌면 개수도 바뀝니다

이 속성은 특정 시점의 숫자를 읽어 옵니다. 새로운 자식을 append()한 뒤 다시 읽으면 증가한 값을, 자식을 remove()한 뒤 다시 읽으면 감소한 값을 얻습니다. 이전에 변수에 저장한 숫자는 자동으로 갱신되지 않습니다.

const before = list.childElementCount;
const item = document.createElement('li');
item.textContent = '새 항목';
list.append(item);
console.log(before, list.childElementCount); // 2, 3

하위 전체의 요소 수가 필요하면 querySelectorAll()처럼 범위를 지정해 조회해야 합니다. 단순히 직접 자식 수가 필요한 경우에는 childElementCount가 의도를 더 정확하게 드러냅니다.

전체 예제: 목록 항목 추가·삭제

다음 코드를 child-element-count.html로 저장해 브라우저에서 엽니다. 첫 번째 항목의 중첩된 strong을 포함해도 처음 표시되는 개수는 2개입니다. 추가·삭제 버튼을 눌러 숫자가 어떻게 변하는지 확인하세요.

<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>자식 요소 개수 세기</title>
</head>
<body>
<ul id="items">
  <li>항목 1 <strong>중첩 강조</strong></li>
  <li>항목 2</li>
</ul>
<button id="add" type="button">항목 추가</button>
<button id="remove" type="button">마지막 항목 제거</button>
<p id="count" aria-live="polite"></p>
<script>
const list = document.querySelector('#items');
const count = document.querySelector('#count');
let nextNumber = 3;

function update() {
  count.textContent = `직접 자식 요소: ${list.childElementCount}개`;
}

document.querySelector('#add').addEventListener('click', () => {
  const item = document.createElement('li');
  item.textContent = `항목 ${nextNumber++}`;
  list.append(item);
  update();
});
document.querySelector('#remove').addEventListener('click', () => {
  list.lastElementChild?.remove();
  update();
});
update();
</script>
</body>
</html>

항목 추가를 한 번 누르면 3개, 마지막 항목 제거를 누르면 다시 2개입니다. 모든 항목을 제거하면 0개가 되며, 한 번 더 제거해도 오류가 나지 않습니다. lastElementChild가 없을 수 있으므로 예제는 옵셔널 체이닝(?.)을 사용합니다.