목차
1. childElementCount
2. children.length
3. 두 속성의 차이점
1. childElementCount
특정 요소의 직속 자식 요소의 수를 반환한다.
사용 방법은 다음과 같다.
const parent = document.getElementById("parent");
console.log(parent.childElementCount);
사용 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="parent">
<div id="child">
<span></span>
</div>
안녕하세요.
<!-- 주석은 카운팅 x -->
</div>
</body>
<script>
const parent = document.getElementById("parent");
console.log(parent.childElementCount);
</script>
</html>
⚠️ 주의 :
1. 직속 자식의 수를 구하는 것이므로, <span> 요소의 갯수는 포함되지 않는다. parent의 직속 자식인 child만 카운팅된다.
2. 텍스트 노드(안녕하세요.)와 주석은 카운팅되지 않는다.
2. children.length
특정 요소의 직속 자식 요소의 수를 반환한다.
사용 방법은 다음과 같다.
const parent = document.getElementById("parent");
console.log(parent.children.length);
사용 예제
childElementCount와 동일하다. 😊
3. 두 속성의 차이점
구분 | childElementCount | children.length |
타입 | 숫자 (number) | 숫자 (number) |
반환 대상 | 자식 요소의 개수 | children는 HTMLCollection, length는 그 개수 |
속성 or 메서드 | 속성 (읽기 전용) | children은 속성, length는 그 속성 |
'HTML, CSS, Javascript' 카테고리의 다른 글
[Javascript] HTML form 새로고침 없이 데이터 보내는 법 (0) | 2025.04.24 |
---|---|
[Javascript] JS 이벤트 시스템, 어떻게 작동할까? (0) | 2025.04.21 |
[Javascript] DOM(The Document Object Model) (0) | 2025.04.20 |
[Javascript] 요소를 붙이는 다양한 방법 (0) | 2025.04.13 |
[Javascript] HTML 문서에 새 요소 붙이는 방법 (0) | 2025.04.12 |