자바스크립트와 HTML

Hyemimi·2022년 9월 11일
0

js

목록 보기
18/18

HTML은 자바스크립트와 CSS를 읽어올 수 있다.

반대로 자바스크립트는 HTML 요소를 가져와 사용할 수 있다.

1. HTML 태그 가져와 수정하기

document.title = "hyemimi"

2. id를 이용해 태그 가져오기

index.html안에 <h1 id="title">Grab me!</h1> 라는 태그가 있다고 하면,

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

위와 같이 해당 태그를 가져옴

  • element의 텍스트 수정
const title = document.getElementById("title");
title.innerText = "Got you!";

3. class를 이용해 태그 가져오기

  • 많은 element를 한번에 가지고 와야할 경우
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>

위의 html 파일의 태그들을 클래스 이름으로 가지고 와야한다면,

const hellos = document.getElementsByClassName("helllo");

getElementsByClassName 함수로 해당 element 리스트를 가져올 수 있다.

4. querySelector : element 검색, 단 하나의 element를 return함, 여러개의 태그가 포함되더라도 첫번째것만 가져옴

아래의 hello라는 클래스에 속하는 h1 태그를 가져와보자

index.html

<div class="hello">
	<h1>Grab me!</h1>
</div>

app.js

const title = document.querySelector(".hello hi");
console.log(title);
// output : <h1>Grab me!</h1>

5. querySelectorAll : element 검색, 해당되는 모든 element를 가져옴

profile
암냠냠

0개의 댓글

관련 채용 정보