개발공부/[JS]바닐라JS로 크롬 앱 만들기(노마드코더)

[#3.1]HTML in Javascript_getElementById란?

개발자 덕구🐾 2023. 12. 17. 15:32
728x90
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>durmi ki</title>
</head>
<body>  
    <h1 class = "hello" id="title"> Grab me ! </h1>
    <script src="app.js"></script>
</body>
</html>

 

 

여기 <body> 안에 <h1> 태그를 삽입하였다. 

h1태그의 text는 "Grab me ! " 이고 id는 "title"이다. 

 

 

 

1. document.getElementById()

 

 

 

getElementById를 통해 ID를 인자로 입력하여 

인자로 입력한 값이 id인 요소를 가지고 올수있다. 

 

위의 이미지는 콘솔창에 document.getElementById()를 입력한 경우이다. 

인자로를 title을 입력하여 id가 title인 요소를 가지고 왔다. 

 

 

 

이렇게 id가 "title"인 값을 hi에 저장하여 console.dir으로 볼수있다. 

 

 

hi의 textContent도 확인할 수 있다. 

 

 

이 상태에서 JS코드를 추가해보자. 

 

 

 


 

 

 

 

다음과 같이 app.js 코드에 id가 title인 친구를 const title 에 넣는다. 

그 title의 innerText를 "Got you!"로 변경한다.

 

 

 

이 변경사항을 저장하고 페이지를 새로고침하면 

 

 

 

 

이렇게 Got you! 가 나온다. 

app.js에서 기존의 Grab me ! 에서 Got you! 로 바꾼것이다. 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형