프론트엔드 센트럴파크 (☞゚ヮ゚)☞

querySelector() / querySelectorAll() 본문

Javascript

querySelector() / querySelectorAll()

자라나라나무나무나 2022. 3. 12. 21:19

querySelector() : 하나의  element를 return해준다.

이름이 같은 class가 여러개 있어도 무조건 첫번째의 element만 가져온다.

 

querySelectorAll() : 여러개의 element를 retrun해준다. (array 형태)

 

HTML

<div class = "title">
	<h1>Hello</h1>
</div>

JS

const content = document.querySelector(".title h1");

JS

만약 id가 주어진다면 (div id = "title")

const content = document.querySelector("#title");

 

결론

const content = document.getElementById("title");
const content = document.querySelector("#title");

두개는 같은 것을 의미한다.

 

※ querySelector 를 더 많이 사용하는 이유

 - css 형태로 가져올 수 있다 ("title h1:first-child");

- id와 class 둘 다 사용가능하다.

- class의 하위의 값도 가져올 수 있다.

 

 

 

'Javascript' 카테고리의 다른 글

innerText()과 innerHTML() 차이점  (0) 2022.03.23
innerHTML()  (0) 2022.03.22
getElementById() / getElementsByClassName() / getElementsByTagName()  (0) 2022.03.12
assigned a value but never used 오류  (0) 2022.03.11
FileReader()  (0) 2022.01.11
Comments