html에 이런 태그가 있다면
<div class="inputBox">
<input type="submit" value="당근" />
<input type="submit" value="토끼" />
<input type="submit" value="찾기" />
<span></span>
<span></span>
<span></span>
</div>
위 태그에서 js를 사용하여 순서대로 각 요소들을 선택해보자
const input1 = document.querySelector(".inputBox input:first-child");
const input2 = document.querySelector(".inputBox input:nth-child(2)");
const input3 = document.querySelector(".inputBox input:nth-child(3)");
const span1 = document.querySelector(".inputBox span:nth-of-type(1)");
const span2 = document.querySelector(".inputBox span:nth-child(5)");
const span3 = document.querySelector(".inputBox span:last-child");
내가 가상선택자를 쓸 때마다 헷깔리는 이유가 있었다
나는 당연하게도 부모태그:가상선택자의 구조로 사용한다고 생각했는데
부모태그 + 해당 순서의 태그:nth-child(n)의 구조로 사용해야했다
순서마다 직접 어떤 태그인지 찾아서 입력해줘야 한다니
대체 왜 이렇게 만든건지 글을 쓰면서도 이해할 수 없다
부모태그 + 해당 태그:nth-of-type(n)을 사용하면
부모태그 속에서 특정 태그만 순서대로 찾을 수 있다