less than 1 minute read

요소 선택을 도와주는 ‘ 선택 메서드 ‘



1. document.getElementById()

: 주어진 문자열과 일치하는 id를 가진 요소를 찾아 객체로 반환한다

문서 내에 주어진 id가 없어 찾지 못하면 null을 반환


[ syntax ]

document.getElementById('id');

[ 구문 연습 - 퀴즈문제 ]

image-20240423002426954

image-20240423002444321

=> id가 ‘unicorn’인 이미지 요소를 image라는 변수에 저장

=> id가 ‘mainheading’인 h1를 heading이라는 변수에 저장



2. document.getElementsByTagName()

: 해당 태그를 모두 선택

Elements 가 복수형인 이유는 해당 태그를 한 번에 한 개 이상을 선택해야 하기 때문


[ syntax ]

document.getElementByTagName('tag');

image-20240423010424618

image-20240423004810359

=> p태그인 세 개의 객체가 반환된다

이것은 인덱스와 길이가 있는 반복 가능한 집합이지만 배열은 아니다


image-20240423005839579



3. document.getElementsByClassName()

: 해당 클래스를 모두 선택


[ syntax ]

document.getElementByClassName('class');


image-20240423010149211

image-20240423010212220

=> 클래스가 ‘name’인 객체를 선택



4. document.querySelector()

: 일치하는 첫 번째 요소를 반환


[ syntax ]

document.quertSelector('tag');
document.querySelector('.class');
document.querySelector('#id')


image-20240423010713197

=> p태그 중 첫 번째 요소인 “안녕하세요”



5. document.querySelectorAll()

: 일치하는 모든 요소 반환


[ syntax ]

document.quertSelectorAll('tag');
document.querySelectorAll('.class');
document.querySelectorAll('#id')


image-20240423010836164

Updated: