[자바스크립트_개념정리] DOM_selector
요소 선택을 도와주는 ‘ 선택 메서드 ‘
1. document.getElementById()
: 주어진 문자열과 일치하는 id를 가진 요소를 찾아 객체로 반환한다
문서 내에 주어진 id가 없어 찾지 못하면 null을 반환
[ syntax ]
document.getElementById('id');
[ 구문 연습 - 퀴즈문제 ]
=> id가 ‘unicorn’인 이미지 요소를 image라는 변수에 저장
=> id가 ‘mainheading’인 h1를 heading이라는 변수에 저장
2. document.getElementsByTagName()
: 해당 태그를 모두 선택
Elements 가 복수형인 이유는 해당 태그를 한 번에 한 개 이상을 선택해야 하기 때문
[ syntax ]
document.getElementByTagName('tag');
=> p태그인 세 개의 객체가 반환된다
이것은 인덱스와 길이가 있는 반복 가능한 집합이지만 배열은 아니다
3. document.getElementsByClassName()
: 해당 클래스를 모두 선택
[ syntax ]
document.getElementByClassName('class');
=> 클래스가 ‘name’인 객체를 선택
4. document.querySelector()
: 일치하는 첫 번째 요소를 반환
[ syntax ]
document.quertSelector('tag');
document.querySelector('.class');
document.querySelector('#id')
=> p태그 중 첫 번째 요소인 “안녕하세요”
5. document.querySelectorAll()
: 일치하는 모든 요소 반환
[ syntax ]
document.quertSelectorAll('tag');
document.querySelectorAll('.class');
document.querySelectorAll('#id')