바닐라JS - HTML in javascript

김현수·2022년 8월 22일

바닐라JS

목록 보기
9/17

HTML을 js로 가져오는 방법

1) HTML의 id를 통해 element 찾기

document.getElementById("아이디 이름");

ex)

<h1 id="title">Grab me!</h1>
const title = document.getElementById("title");

받아온 element의 html 내용 바꾸는 방법

title.innerTEXT = "Got you!";

2) HTML의 class를 통해 element 찾기

document.getElementByClassName("클래스 이름");

ex)

<h1 class="hello">Grab me!</h1>
const hello = document.getElementByClassName("hello");

3) element를 css 방식으로 찾기

ex)

<div class="hello">
	<h1>Grab me!</h1>
</div>
const title = document.querySelector(".hello h1");
//class hello를 찾고 그 안에 있는 h1을 찾음

querySelector는 첫번째 element만 가져옴
모든 element를 가져오고 싶다면 querySelectorAll을 사용하면 됨

4) querySelectorAll

selector 안의 조건에 부합하는 모든 element를 가져다줌

<div class="hello">
	<h1>Grab me1!</h1>
</div>
<div class="hello">
	<h1>Grab me2!</h1>
</div>
<div class="hello">
	<h1>Grab me3!</h1>
</div>
const title = document.querySelectorAll(".hello h1");
//querySelectorAll은 세 개의 h1이 들어있는 Array를 가져다줌

0개의 댓글