본문 바로가기
Javascript: to do list

07 html , javascript에서 html을 다루기

by From.h 2023. 5. 30.
728x90
반응형

 

 

 javascript에서 html을 다루는 방식

 

 

 

 

먼저 html에 body안에 <h1> 제목을 만들고, 그 제목의 class 이름과 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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <h1 class="hello" id="title">Come on me!</h1>
    <script src="app.js"></script>
</body>
</html>
 
 
 
 

 

 

이제 javascript에서 id를 통해 element를 오브젝트로 불러와서 변경하는 작업을 해보자.

먼저, 콘솔에 title이라는 id를 불러와 오브젝트의 프로퍼티를 살펴보자

콘솔에서 작성했던 구문을 다음과 같이 js파일에 작성해서 콘솔로 확인해 보자.

title이라는 id를 통해 element를 불러와 title에 할당했고,

콘솔에 그 dir 오브젝트 정보를 모두 모여달라고 했다.

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

console.dir(title);
 

 

 

위에 보면, className = hello, id = "title", innerText = "Come on me!"라는 오브젝트가 존재하는 것을 확인할 수 있다.

이것이 <h1> title 하나에 속해있는 모든 정보들이며, 이 element를 우리는 이용할 수 있는 것이다.

 

예를 들어 위 html이 가지고 있는 오브젝트들 중에서 innertext를 변경한다고 치자.

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

title.innerText = "Go ahead!!";
 
 
 
 
이렇게 작성하고 element를 확인해보면,
 
 

 

이렇게 <h1> title의 innerText가 바뀐 걸 알 수 있다.

이게 가능한 것은 html 파일에서 우리가 id = title를 부여했고,

js파일에서 그 id를 통해 불러왔으며,

이 element를 js파일에서 수정해서 업데이트했기 때문이다.

 

 

 

 

 

 

 

BR. h

 

 

 

728x90
반응형