자바스크립트와 HTML
이 글은 자바스크립트와 HTML에 대해 설명합니다.
YouTube Video
javascript-html-dom.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 2em;
14 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
15 background-color: #f7f9fc;
16 color: #333;
17 line-height: 1.6;
18 }
19
20 .container {
21 max-width: 800px;
22 margin: 0 auto;
23 padding: 1em;
24 background-color: #ffffff;
25 border: 1px solid #ccc;
26 border-radius: 10px;
27 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
28 }
29
30 h1, h2 {
31 font-size: 1.5rem;
32 color: #007bff;
33 margin-top: 0.5em;
34 margin-bottom: 0.5em;
35 border-left: 5px solid #007bff;
36 padding-left: 0.6em;
37 background-color: #e9f2ff;
38 }
39
40 button {
41 display: block;
42 margin: 1em auto;
43 padding: 0.75em 1.5em;
44 font-size: 1rem;
45 background-color: #007bff;
46 color: white;
47 border: none;
48 border-radius: 6px;
49 cursor: pointer;
50 transition: background-color 0.3s ease;
51 }
52
53 button:hover {
54 background-color: #0056b3;
55 }
56
57 #output {
58 margin-top: 1em;
59 background-color: #1e1e1e;
60 color: #0f0;
61 padding: 1em;
62 border-radius: 8px;
63 min-height: 200px;
64 font-family: Consolas, monospace;
65 font-size: 0.95rem;
66 overflow-y: auto;
67 white-space: pre-wrap;
68 }
69
70 .highlight {
71 outline: 3px solid #ffc107; /* yellow border */
72 background-color: #fff8e1; /* soft yellow background */
73 transition: background-color 0.3s ease, outline 0.3s ease;
74 }
75
76 .active {
77 background-color: #28a745; /* green background */
78 color: #fff;
79 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
80 transition: background-color 0.3s ease, box-shadow 0.3s ease;
81 }
82 </style>
83</head>
84<body>
85 <div class="container">
86 <h1>JavaScript Console</h1>
87 <button id="executeBtn">Execute</button>
88 <div id="output"></div>
89 </div>
90
91 <div class="container">
92 <h2>HTML Sample</h2>
93 <div id="content">Hello, World!</div>
94 <button id="changeText">Change Text</button>
95 </div>
96
97 <script>
98 // Override console.log to display messages in the #output element
99 (function () {
100 const originalLog = console.log;
101 console.log = function (...args) {
102 originalLog.apply(console, args);
103 const output = document.getElementById('output');
104 output.textContent += args.map(String).join(' ') + '\n';
105 };
106 })();
107
108 document.getElementById('executeBtn').addEventListener('click', () => {
109 // Prevent multiple loads
110 if (document.getElementById('externalScript')) return;
111
112 const script = document.createElement('script');
113 script.src = 'javascript-html-dom.js';
114 script.id = 'externalScript';
115 //script.onload = () => console.log('javascript-html-dom.js loaded and executed.');
116 //script.onerror = () => console.log('Failed to load javascript-html-dom.js.');
117 document.body.appendChild(script);
118 });
119 </script>
120</body>
121</html>
자바스크립트의 window
객체
window
객체는 자바스크립트에서 브라우저 환경의 전역 객체로, 웹 페이지와 브라우저 창과 관련된 기능과 정보를 제공합니다. window
객체는 브라우저의 전역 범위이므로 브라우저에서 실행되는 모든 자바스크립트 코드는 window
객체의 일부가 됩니다. window
객체는 브라우저 환경에서 자바스크립트를 실행하는 데 중요한 역할을 하며, 다양한 API와 속성을 제공합니다.
window
객체의 주요 기능
속성
1// Get and display the document's title
2console.log(`Title: ${window.document.title}`);
3
4// Get and display the current URL
5console.log(`URL: ${window.location.href}`);
6
7// Go back to the previous page
8// Note: this will navigate back in history, so be careful when running it
9console.log("Navigating back to the previous page...");
10window.history.back();
11
12// Display the browser's user agent
13console.log(`User Agent: ${window.navigator.userAgent}`);
14
15// Display the width and height of the viewport
16console.log(`Viewport Width: ${window.innerWidth}`);
17console.log(`Viewport Height: ${window.innerHeight}`);
window.document
: 현재 HTML 문서에 접근.window.location
: 현재 URL 및 브라우저 탐색을 관리.window.history
: 브라우저의 기록 정보에 접근하고 앞으로 및 뒤로 탐색 가능.window.navigator
: 브라우저 및 디바이스에 대한 정보를 제공.window.innerWidth
/window.innerHeight
: 뷰포트의 너비와 높이를 가져오기.
메서드
1// Show an alert
2window.alert('Hello, this is an alert!');
3
4// Show a confirmation dialog
5if (window.confirm('Are you sure you want to proceed?')) {
6 console.log('User clicked OK');
7} else {
8 console.log('User clicked Cancel');
9}
10
11// Show a prompt dialog
12const userInput = window.prompt('Please enter your name:');
13console.log(`Hello, ${userInput}!`);
14
15// Open a new tab
16window.open('https://www.example.com', '_blank');
17
18// Display a message after 3 seconds
19window.setTimeout(() => {
20 console.log('This message appears after 3 seconds!');
21}, 3000);
22
23// Display a message every second
24const intervalId = window.setInterval(() => {
25 console.log('This message appears every second!');
26}, 1000);
27
28// Clear the interval after 5 seconds
29setTimeout(() => {
30 clearInterval(intervalId);
31 console.log('Interval cleared.');
32}, 5000);
window.alert()
: 알림 대화 상자를 표시.window.confirm()
: 사용자 확인을 요청하는 대화 상자를 표시하고 확인 또는 취소 결과를 반환.window.prompt()
: 사용자 입력을 요청하는 대화 상자를 표시하고 입력된 값을 가져옴.window.open()
: 새 창이나 탭을 엶.window.setTimeout()
/window.setInterval()
: 일정 시간 이후 또는 정기적으로 함수를 실행하는 타이머를 설정.
이벤트 처리
1// Display a message when the page is fully loaded
2window.onload = () => {
3 console.log('Page is fully loaded!');
4};
5
6// Display a message when the window is resized
7window.onresize = () => {
8 console.log('Window resized! New size:', window.innerWidth, 'x', window.innerHeight);
9};
10
11// Display a message when the page is being scrolled
12window.onscroll = () => {
13 console.log('Page is being scrolled!');
14};
window.onload
: 이 이벤트는 페이지가 완전히 로드되었을 때 트리거됩니다.window.onresize
: 이 이벤트는 창의 크기가 조정될 때 발생합니다.window.onscroll
: 이 이벤트는 사용자가 페이지를 스크롤할 때 발생합니다.
전역 변수로서의 역할
1var myVar = 10;
2console.log(window.myVar); // 10
window
객체는 전역 변수와 함수를 포함합니다. 즉, 선언된 변수와 함수는 자동으로window
의 속성이 됩니다.
JavaScript에서의 DOM 조작
JavaScript DOM (문서 객체 모델) 조작은 웹 페이지의 요소와 동적으로 상호작용하는 데 사용됩니다. DOM은 HTML 문서 구조를 트리 형태로 나타내며, JavaScript를 사용해 구조를 변경하고 페이지의 표시를 제어할 수 있습니다.
DOM 기초
DOM은 웹 페이지의 HTML을 객체로 처리하여 요소와 속성에 접근하고 수정할 수 있도록 합니다. HTML 문서에 접근하려면 document
객체를 사용하십시오.
DOM 요소 가져오기
JavaScript는 DOM의 요소에 접근하기 위한 여러 가지 메서드를 제공합니다.
document.getElementById()
:id
속성으로 요소를 가져옵니다.document.getElementsByClassName()
: 클래스 이름으로 요소들을 가져옵니다.HTMLCollection
을 반환합니다.HTMLCollection
은 DOM의 변화를 실시간으로 반영하는 라이브 컬렉션입니다.document.getElementsByTagName()
: 태그 이름으로 요소들을 가져옵니다.HTMLCollection
을 반환합니다.document.querySelector()
: CSS 선택자를 사용하여 첫 번째로 일치하는 요소를 가져옵니다.document.querySelectorAll()
: CSS 선택자를 사용하여 모든 일치하는 요소를 가져옵니다.NodeList
를 반환합니다.NodeList
는 가져온 시점의 상태만 저장하며 이후 DOM의 변화를 반영하지 않는 정적 컬렉션입니다.
예시: getElementById
및 querySelector
1<div id="content">Hello, World!</div>
2<button id="changeText">Change Text</button>
1const content = document.getElementById('content');
2console.log(content.textContent); // "Hello, World!"
3
4const button = document.querySelector('#changeText');
DOM 조작
가져온 요소를 대상으로 다양한 작업을 수행할 수 있습니다.
텍스트 변경하기
요소의 텍스트를 변경하려면 textContent
또는 innerHTML
을 사용하십시오.
textContent
: 요소의 텍스트 내용을 가져오거나 변경. HTML 태그는 해석되지 않습니다.innerHTML
: 요소의 HTML 콘텐츠를 가져오거나 변경. HTML 태그가 포함된 문자열도 처리됩니다.
1content.textContent = 'Hello, world!'; // Change the text
2button.innerHTML = '<strong>Click to change</strong>'; // Change including HTML
속성 변경하기
setAttribute()
와 getAttribute()
를 사용하여 요소 속성을 변경하세요.
1button.setAttribute('disabled', 'true'); // Disable the button
2const id = content.getAttribute('id'); // Get the "content"
3console.log(id);
CSS 변경하기
style
속성을 사용하여 CSS 스타일을 변경하세요.
1content.style.color = 'red'; // Change the text color to red
2content.style.fontSize = '20px'; // Change the font size
클래스 조작
classList
를 사용하여 요소에 클래스 추가 또는 제거하기.
add()
: 클래스를 추가합니다.remove()
: 클래스를 제거합니다.toggle()
: 클래스가 존재하는지에 따라 추가하거나 제거합니다.contains()
: 클래스가 존재하는지 확인합니다.
1content.classList.add('highlight'); // Add a class
2button.classList.toggle('active'); // Toggle a class
DOM 요소의 생성 및 삭제
새 요소 생성하기
document.createElement()
을 사용해 새로운 요소를 생성하고 DOM에 추가하세요.
1const newDiv = document.createElement('div'); // Create a new div element
2newDiv.textContent = 'This is a new element';
3document.body.appendChild(newDiv); // Append to the body element
요소 삭제
remove()
메서드를 사용하여 요소를 삭제하세요.
1newDiv.remove(); // Remove the created element
이벤트 추가하기
DOM 조작의 일환으로 사용자 상호작용에 반응하는 이벤트 핸들러를 추가할 수 있습니다. addEventListener()
를 사용하여 클릭 및 키보드 상호작용 같은 이벤트를 처리하세요.
1button.addEventListener('click', () => {
2 content.textContent = 'The text has been changed';
3});
이 예제에서는 버튼을 클릭하면 #content
요소의 텍스트가 변경됩니다.
DOM 트리 탐색하기
DOM을 탐색하여 부모 및 형제 요소에 접근할 수 있습니다.
parentNode
: 부모 노드에 접근합니다.childNodes
: 자식 노드들에 접근합니다. HTML 태그와 같은 요소 노드뿐만 아니라 텍스트 노드, 주석 노드 등 모든 종류의 노드에 접근할 수 있습니다.firstChild
/lastChild
: 첫 번째 및 마지막 자식 요소에 접근합니다.nextSibling
/previousSibling
: 다음 및 이전 형제 요소에 접근합니다.
1const parent = content.parentNode; // Get the parent element
2const firstChild = parent.firstChild; // Get the first child element
3console.log(firstChild);
예제: 목록에 새 항목 추가하기
여기에는 목록에 새 항목을 추가하는 예제가 있습니다.
1// Get the container element where the HTML will be inserted
2const content = document.getElementById('content');
3
4// Create the <ul> element with id="list"
5const list = document.createElement('ul');
6list.id = 'list';
7
8// Add initial list items
9const item1 = document.createElement('li');
10item1.textContent = 'Item 1';
11list.appendChild(item1);
12
13const item2 = document.createElement('li');
14item2.textContent = 'Item 2';
15list.appendChild(item2);
16
17// Create the <button> element with id="addItem"
18const addItemButton = document.createElement('button');
19addItemButton.id = 'addItem';
20addItemButton.textContent = 'Add Item';
21
22// Append the list and button to the content container
23content.appendChild(list);
24content.appendChild(addItemButton);
25
26// Add event listener to the button
27addItemButton.addEventListener('click', () => {
28 const newItem = document.createElement('li');
29 newItem.textContent = 'New Item';
30 list.appendChild(newItem);
31});
이 코드에서 "항목 추가" 버튼을 클릭하면 목록에 새 <li>
요소가 추가됩니다.
요약
- JavaScript DOM 조작을 사용하면 HTML 문서 내의 요소를 가져오고, 변경하고, 생성하고, 삭제할 수 있습니다.
getElementById()
및querySelector()
와 같은 메서드를 사용하여 요소를 가져올 수 있습니다.textContent
또는innerHTML
을 사용해 텍스트와 HTML을 변경하고,setAttribute()
를 사용해 속성을 조작합니다.createElement()
을 사용해 새 요소를 생성하고remove()
를 사용해 이를 삭제할 수 있습니다.- 이벤트 처리를 통해 사용자 조작에 반응하는 대화형 웹 페이지를 만들 수 있습니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.