[JS] 부모, 자식, 형제 찾기 - node, element

AREUM·2022년 12월 1일
2

Javascript실행

목록 보기
1/7
post-thumbnail

자주 사용 될 거 같아서 정리해 본다.

node와 element의 차이점

1. node 찾기

계층 구조 중 node는 제일 꼭대기라고 생각하시면 될 거 같다.
element, text, comment 등.. 여러 항목을 포함되어 있다.


위 이미지를 보자면, 속성을 통해서 node에 접근할 수 있다.

💡깨알 영단어💡
property : 속성
parent : 부모
child : 자식
sibling : 형제
return : 반환

1-1. 부모 노드 ( parent node )

  • parentNode : 부모 노드를 찾는 속성을 찾는다.

1-2. 자식 노드 (child node )

  • childNodes : 자식 노드 목록을 NodeList 형태로 찾는다.
    ( 자식 노드를 찾는 속성 - li 안에 p태그가 3개가 있다면 모든 p태그를 찾는다. )
  • firstChild : 자식 노드 중, 첫번째 자식 노드를 찾는다.
  • listChild : 자식 노드 중, 마지막 자식 노드를 찾는다.

1-3. 형제 노드 ( sibling node )

  • previousSibling : 같은 레벨의 노드 중, 이전 노드를 찾는다.
  • nextSibling : 같은 레벨의 노드 중, 다음 노드를 찾는다.

2. element 찾기

nodeType 중 의 한 종류다.
element는 <p></p> <div></div> <ul></ul> 등을 사용한 요소이다.

2-1. 부모 요소 ( parent element )

  • parentElement : 부모 요소를 찾는다.

2-2. 자식 요소 ( child element )

  • children : 자식 요소 목록을 'HTMLCollection' 형태로 찾는다.
  • firstElementChildren : 자식 요소 중, 첫번째 요소를 찾는다.
  • lastElementChildren : 자식 요소 중, 마지막 요소를 찾는다.

2-3. 형제 요소 ( sibling element )

  • previousElementSibling : 같은 레벨의 요소 중, 이전 요소를 찾는다.
  • nextElementSibling : 같은 레벨의 요소 주우, 다음 요소를 찾는다.

응용 : 부모요소의 이전 형제

<ul>
  <li class="one"></li>
  <li class="two">
    <p class="current">this</p>
  </li>
  <li class="three"></li>
</ul>
// <p></p>태그 인 element요소를 me 변수에 담기
const me = document.querySelector('.current');
// me의 부모요소의 형제요소인 이전요소를 찾아 answer변수에 담기
const answer = me.parentNode.previousElementSibling;

console.log(answer);	// li.one 이 나온다.

갑자기 궁금해 졌다.
경우의 수를 해보았다.

const me = document.querySelector('.current');
const answer = me.parentNode.previousSibling;	// 부모노드->형제이전노드
const answer2 = me.parentElement.previousElementSibling;	// 부모요소->형제이전요소
const answer3 = me.parentNode.previousElementSibling;	// 부모노드->형제이전요소
const answer4 = me.parentElement.previousSibling;	// 부모요소->형제이전노드

console.log(answer, answer2, answer3, answer4);

결과는 이렇다.

그냥 생각
console.log찍어보고 상황에 맞는 필요한 속성을 사용하면 될거같다.
ex) 태그를 찾으려면 element를 탐색하고, 태그 내에 text를 찾으려면, node를 탐색하면 될거같다.

참고 사이트

profile
어깨빵으로 부딪혀보는 개발끄적이는 양씨 인간

0개의 댓글