티스토리 뷰

반응형

getElementById()는 무엇인가?

element = document.getElementById(id);

id를 통해 엘리먼트를 반환한다. 만약 document에 구체적인 ID의 엘리먼트가 없다면 null을 반환한다.

querySelector()는 무엇인가?

element = document.querySelector(selectors);

selector의 구체적인 그룹과 일치하는 document안 첫번째 엘리먼트를 반환한다. 일치하는게 없으면 null반환한다.

 

querySelector vs selectElementById

<form id="userForm">

<input id="username" type="text" value="Guilherme" />

</form>

위와 같은 코드가 있다고 가정해보자. 우리는 username 요소를 얻고 싶고 이를 변수에 할당하고 싶다.

첫번째로 getElemenyById를 통해 해보자!

var username = document.getElementById("username");

그리고 이번에는 querySelector를 통해 같은 요소를 얻어보자!

var username = document.querySelector("#userForm #username");

위 코드를 보면 알 수 있듯이,querySelector를 통해 우리가 원하는 엘리먼트를 선택하는 것은 더 구체적이고 한정적이다. 그러나 결과는 같다!

querySelectorAll vs selectElementByClassName

아래 코드가 있다고 가정해보자~

<form id="productForm">

<input id="productOne" class="product" type="text" value="Product 1" />

<input id="productTwo" class="product" type="text" value="Product 2" />

<input id="productThree" class="product" type="text" value="Product 3" />

</form>

우리는 모든 products 엘리먼트를 얻고 싶고 이를 변수에 할당하고 싶다.
getElementByClassName을 통해 사용해보자.

var products = document.getElementsByClassName("product");

이번에는 querySelectorAll을 통해 같은 엘리먼트를 얻어보고자 한다.

var products = document.querySelectorAll("#productForm .product");

음.. 결과는 거의 같다. 그러나,getElementsByClassName은 HTMLCollection에 리턴이 되고 querySelectorAll은 NodeList에 리턴이 된다.

💘 그럼 여기서 HTMLcollection은 뭐고 NodeList는 무엇인가??
우선, 간단하게 설명해보면 둘 다 배열과 같이 각 항목을 접근하기 위한 인덱스를 제공한다고 한다. HTMLCollection의 항목은 name, id 속성으로도 접근이 가능하지만, NodeList의 항목은 인덱스 번호로만 접근이 가능하다.

마지막 결론

만약 더 구체적인 엘리먼트를 선택하고 싶다면, querySelector그리고 querySelectorAll을 사용해보자!
그러나 위 둘에 비해 getElementByID가 더 빠르고 더 잘 지원이 된다는 것을 알아두자. 참고한 2명의 개발자들은 querySelector대신에 getElementById를 더많이쓴다고 말하고 있다.

참고:https://guinatal.github.io/queryselector-vs-getelementbyid
https://whatabouthtml.com/difference-between-getelementbyid-and-queryselector-180

반응형

'WEB > Javascript' 카테고리의 다른 글

EVENT란? - (1)이벤트의 종류  (0) 2022.03.02
DOM (Document Object Model)  (0) 2022.03.01
axios 개념 정리  (0) 2021.12.08
insertAdjacentHTML 과 innerHTML의 차이점  (0) 2021.10.26
Vanilla-JS/Javascript/node.js 차이점  (0) 2021.10.24
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함