결론부터 말씀드리면 getElementById가 조금 더 빠르기 때문에 id가 있는 Element를 찾는 경우에는 getElementById를 사용하고 보다 정교하게 Element를 찾는 작업이 들어가면 querySelector를 사용하는게 좋습니다.
1. getElementById
- 주어진 ID 문자열과 일치하는 속성을 가진 Element를 찾아 반환합니다.
- 결과가 없다면 null
document.getElementById(id);
2. querySelector
- 제공한 선택자 또는 선택자 그룹과 일치하는 문서 내 첫번째 Element를 반환합니다.
- 결과가 없다면 null
- 백슬래시("\")를 사용해 특수문자를 이스케이프 해야합니다.
document.querySelector(selectors);
예제
See the Pen getElementBtId vs querySelector by Park, Chungman (@pcm9881) on CodePen.
성능
getElementId가 querySelector보다 1.2배 빠르다 (HTML 구조나 개발 환경에 따라 달라 질 수 있습니다)
[javascript benchmark]: https://jsbench.me/
JSBench.me - JavaScript performance benchmarking playground
jsbench.me
참조
[MDN getElementById]: https://developer.mozilla.org/ko/docs/Web/API/Document/getElementById
Document.getElementById() - Web API | MDN
Document.getElementById() 메서드는 주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 Element 객체를 반환합니다. ID는 문서 내에서 유일해야 하기 때문에 특정 요소를 빠르게 찾을
developer.mozilla.org
[MDN querySelector]: https://developer.mozilla.org/ko/docs/Web/API/Document/querySelector
Document.querySelector() - Web API | MDN
Document.querySelector() 는 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환합니다. 일치하는 요소가 없으면 null을 반환합니다.
developer.mozilla.org
'Programing Language > Javascript' 카테고리의 다른 글
[Javascript] console.log() JSON pretty print (0) | 2023.06.12 |
---|---|
[Javascript] 현재 화면 높이 구하기 (0) | 2023.04.03 |
[Javascript] 문자열 자르기 (slice, substr, substring) (0) | 2023.03.22 |
[Javascript] fetch 파일 업로드 예제 (0) | 2023.02.21 |
[Javascript] A form label must be associated with a control. (0) | 2022.11.01 |
댓글