html + css + javascript

[바닐라 JS로 크롬 앱 만들기] document, 요소 가져오기

sping2 2023. 6. 20. 23:01

콘솔에 document라고 치면 내가 작성한 html을 가져올 수 있다.

document는 html을 가리키는 객체이다.

 

document가 html를 가리키기 때문에, html에 작성한 title도 가져올 수 있다.

 

object의 property를 수정했던것처럼

document.title을 수정할 수 있다.

수정하면, 창의 이름이 바뀐다! 

 

자바스크립트가 HTML에 연결되어 있다.

자바스크립트는 document를 통해 HTML에 접근할 수 있다!


HTML 파일에 접근하기 1 : getElementById()

html 파일에 이렇게 적은 후

<h1 id="title">Grab me!</h1>

콘솔에서 이 요소에 접근하기

 

콘솔에서 접근한 것처럼, 자바스크립트 파일에서 접근할 수 있다

요소 확인하기

const title = document.getElementById('title');

console.dir(title);

console.dir()는 요소를 자세하게 보여준다.

 

innerText

자바스크립트에서 요소에 접근한 후 

innerText 함수를 통해 수정할 수 있다.

const title = document.getElementById('title');

title.innerText = 'Got you!';

 

HTML 파일에 접근하기 2 : getElementByClassName

class를 설정한 요소들은 getElementByClassName를 통해 접근할 수 있다.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>Momentum</title>
    </head>
    <body>
        <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>
        <script src="app.js"></script>
    </body>
</html>
const hellos = document.getElementsByClassName('hello');

console.log(hellos);

 

# div 안의 h1에 접근하려면?

## 방법 1 : getElementsByTagName

모든 태그를 가져온다. 

const title = document.getElementsByTagName('h1');

console.log(title);

이 경우 h1 태그가 하나밖에 없기 때문에 배열 안에 요소가 하나만 존재한다.

## 방법 2 : querySelector

querySelector는 element를 CSS 방식으로 검색할 수 있다.
hello 안에 있는 h1만 가져올 수 있다.

const title = document.querySelector('.hello h1');

console.log(title);

 

# querySelector, querySelectorAll 비교

## querySelector의 경우

가장 먼저 나오는 하나의 요소만 가져온다.

## querySelectorAll의 경우

모든 요소를 가져온다.

 

class = "hello"를 가져오는 경우 querySelector(".hello")

id = "hello"를 가져오는 경우 querySelector("#hello")