본문 바로가기
Dev/JavaScript

[노마드코더] 바닐라 JS로 크롬 앱 만들기 - #3.1

by MICOSA 2021. 11. 27.

#2.15 HTML in Javascript

 

 

들어가며

특정한 무언가를 가져와보자.

우린 HTML에서 항목들을 가지고 와서, JavaScript를 통해 항목들을 변경할 것임.

우리가 JavaScript로 정보를 가지고 올 수 있는 방법은

document 객체와 element를 가져오는 수많은 함수들을 이용하는 것임.

이번 강의에서 전부 알아볼 것임. 

 

 

 

개념

<!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">
    <title>Momentum App</title>
</head>
<body>
    <h1 id="title">Grab me!</h1>
</body>
</html>

 

document.getElementById("title") 결과값

document.getElementById()를 이용하여

h1의 id로 값을 가져올 수 있음.

여기서 우리는 JavaScript에서 위 HTML을 가져오는 것임. 

JavaScript는 위 HTML의 element를 가지고 오지만, HTML 자체를 보여주지는 않음.

 

 

 

 


 

consol.dir()

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

console.dir(title);

결과값

id값이 title인 <h1> 태그 하나에서 가져올 수 있는 많은 것들을 볼 수 있음.

 

 

 


 

autofocus

현재 autofocus 값이 false.

h1에 autofocus를 추가

<!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">
    <title>Momentum App</title>
</head>
<body>
    <h1 autofocus id="title">Grab me!</h1>
</body>
</html>

 

결과값

autofocus가 true로 바뀐 것을 확인할 수 있음.

 

 

 

 


 

className

className 설정 전

h1에 class를 추가해줌.

<!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">
    <title>Momentum App</title>
</head>
<body>
    <h1 class="hello" id="title">Grab me!</h1>
</body>
</html>

 

결과값

 

 

 


 

innerText

JavaScript를 통해 HTML 텍스트를 변경할 수 있음.

 

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

title.innerText = "Got you!";

 

 JavaScript에 의해 변경된 텍스트

 

 

 


 

 

이렇듯 javascirpt에서 id가 title이라는 항목을 가져오고 있음.

javascirpt에서 h1의 className 및 id를 확인할 수도 있음.

 

<!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">
    <title>Momentum App</title>
</head>
<body>
    <h1 class="helllllo!!!!" id="title">Grab me!</h1>
</body>
</html>

 

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

console.log(title.id);
console.log(title.className);

결과값

댓글