table의 index 쉽게 찾기 글에서 다룬 내용이다.
event.target.parentNode
처럼 사용하여 부모 태그를 선택할 수 있다.
event.target.children
처럼 사용하여 자식 태그들을 가져올 수 있다.
유사 배열 객체란 배열처럼 생긴 객체를 말한다.
chrome에서 console을 찍어 보았을 때 괄호의 숫자 앞에 다른 이름이 붙으면 대부분 유사 배열 객체이다.
// 틱택토 게임에서 따온 코드
<header>
<div>
<span>안녕하세요</span>
<button>클릭</button>
</div>
</header>
<script>
console.log(document.querySelector('span').parentNode.children);
console.log(document.querySelector('span').parentNode.children.indexOf('span'));
</script>
사진에서 보이다시피 배열의 내장 메소드인
indexOf
를 사용할 수 없는데, 이는 이름에서도 알 수 있듯이 배열이 아니라 객체이기 때문이다.
console.log(Array.from(document.querySelector('span').parentNode.children));
console.log(Array.from(document.querySelector('span').parentNode.children).indexOf($span));