JavaScript를 사용하여 요소의 자식 요소 수를 얻는 방법은 무엇입니까?

2876 단어 javascript
Originally posted here!

상위 요소 내부의 하위 요소 수를 얻으려면 다음을 사용할 수 있습니다.
childElementCount
JavaScript의 DOM 요소에 있는 속성.

다음과 같이 내부에 일부 div 요소가 있는 paragraph 요소가 있다고 가정해 보겠습니다.

<div>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
</div>


이제 paragraph 요소의 childElementCount 속성을 사용하여 자식div 요소의 수를 알아보겠습니다.

// get reference to the div element
const div = document.querySelector("div");

// get the length of children
// inside the div element
const lengthOfChildren = div.childElementCount;

console.log(lengthOfChildren); // 13


JSBin에 있는 이 예제를 참조하세요.

😃 유용하셨다면 공유해 주세요.

좋은 웹페이지 즐겨찾기