본문 바로가기
Front-end School/JS

[Javascript] DOM 기초 - HTML in Javascript

by .LUKA 2022. 2. 18.
728x90

다음과 같은 코드를 작성해보았다.

<!DOCTYPE html>
<html lang="ko">
<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>Luka</title>
<style>
</style>
</head>
<body>
     <h1 id="hi">Hello Luka</h1>
</body>
</html>

전에 글에서 언급했듯이 Javascript 에서 정보를 가져올 수 있는 방법은 Document 객체와, element를 가져오는 수많은 함수를 이용하는 것이다.

 

그렇다면 HTML을 Javascript로 가져와서 사용할 수 있는 방법들을 쉬운 예로 알아보자.

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

먼저 getElementById로 h1의 id를 가져온다.

브라우저를 실행시킨 후 콘솔 창에 

 

console.dir(hi)를 입력하면 다음과 같이 실행이 된다.

콘솔 결과창

수많은 오브젝트 속에서 innerText 속에서 내가 작성한 HTML 내용을 확인할 수 있다.

콘솔창에 다음과 같은 코드를 입력하고 실행시켜보겠다.

hi.innerText = "Bye Luka"

 

결과

 

이처럼 우리는 Javascript 를 통해 HTML 요소들을 가져올 수 있고,

또한 가져온 요소들을 변경시킬 수 있다.

 

 

Ref. 노마드 코더

https://nomadcoders.co/javascript-for-beginners/lobby

 

Watch Now – 노마드 코더 Nomad Coders

 

nomadcoders.co

728x90