자바스크립트

웹을 움직이는 언어, 자바스크립트! ES6+, Vue, React, Node.js 등 모던 JS 생태계를 깊이 있게 탐구하는 공간입니다.

2025.02.22 02:55

Jquery .children(): 자식 요소 선택하기

  • 나우호스팅 21일 전 2025.02.22 02:55
  • 12
    0

jquery .children()


자바스크립트의 .children() 메서드

자바스크립트의 `.children()` 메서드는 DOM 요소의 자식 요소를 반환합니다. 이 메서드는 jQuery의 메서드이지만, 자바스크립트에서 직접 사용할 수 있습니다.

자바스크립트의 .children() 메서드 사용 예제


#hostingforum.kr
javascript

// HTML

<div id="parent">

  <p>자식 1</p>

  <p>자식 2</p>

  <p>자식 3</p>

</div>



// 자바스크립트

const parent = document.getElementById('parent');

const children = parent.children;



console.log(children); // HTMLCollection(3) [p, p, p]



// 각 자식 요소에 접근

for (let i = 0; i < children.length; i++) {

  console.log(children[i].textContent); // 자식 1, 자식 2, 자식 3

}



자바스크립트의 .children() 메서드와 jQuery의 차이점


jQuery의 `.children()` 메서드는 jQuery 객체를 반환합니다. 반면에 자바스크립트의 `.children` 속성은 HTMLCollection 객체를 반환합니다.

#hostingforum.kr
javascript

// jQuery

$('#parent').children().each(function() {

  console.log($(this).text()); // 자식 1, 자식 2, 자식 3

});



// 자바스크립트

const parent = document.getElementById('parent');

const children = parent.children;



Array.from(children).forEach(child => {

  console.log(child.textContent); // 자식 1, 자식 2, 자식 3

});



자바스크립트의 .children() 메서드와 .childNodes 메서드의 차이점


`.children()` 메서드는 자식 요소만 반환합니다. 반면에 `.childNodes` 속성은 자식 요소뿐만 아니라 텍스트 노드, 주석 노드, 기타 노드도 반환합니다.

#hostingforum.kr
javascript

// HTML

<div id="parent">

  <p>자식 1</p>

  <p>자식 2</p>

  <p>자식 3</p>

</div>



// 자바스크립트

const parent = document.getElementById('parent');

const children = parent.children;

const childNodes = parent.childNodes;



console.log(children); // HTMLCollection(3) [p, p, p]

console.log(childNodes); // NodeList(5) [ #text, p, #text, p, #text ]



// 각 자식 요소에 접근

for (let i = 0; i < children.length; i++) {

  console.log(children[i].textContent); // 자식 1, 자식 2, 자식 3

}



// 각 자식 노드에 접근

for (let i = 0; i < childNodes.length; i++) {

  console.log(childNodes[i].nodeType); // 3, 1, 3, 1, 3

}



결론


자바스크립트의 `.children()` 메서드는 DOM 요소의 자식 요소를 반환합니다. 이 메서드는 jQuery의 메서드이지만, 자바스크립트에서 직접 사용할 수 있습니다. `.children()` 메서드는 자식 요소만 반환하며, `.childNodes` 속성은 자식 요소뿐만 아니라 텍스트 노드, 주석 노드, 기타 노드도 반환합니다.

이 게시물에 포함된 라이브러리

[PHP_CONFIG] from - HTTP 요청 시 기본 From 헤더 값
[PHP] log - 자연로그
[PHP] each - 배열에서 현재 키와 값 쌍을 반환하고 배열 커서를 이동합니다.
[PHP] Array - 배열 생성
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 자바스크립트 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 35건 / 1 페이지

검색

게시물 검색