자바스크립트와 HTML
이 글은 자바스크립트와 HTML에 대해 설명합니다.
YouTube Video
자바스크립트의 window
객체
window
객체는 자바스크립트에서 브라우저 환경의 전역 객체로, 웹 페이지와 브라우저 창과 관련된 기능과 정보를 제공합니다. window
객체는 브라우저의 전역 범위이므로 브라우저에서 실행되는 모든 자바스크립트 코드는 window
객체의 일부가 됩니다. window
객체는 브라우저 환경에서 자바스크립트를 실행하는 데 중요한 역할을 하며, 다양한 API와 속성을 제공합니다.
window
객체의 주요 기능
속성
1// Get and display the document's title
2console.log(window.document.title);
3
4// Get and display the current URL
5console.log(window.location.href);
6
7// Go back to the previous page
8window.history.back();
9
10// Display the browser's user agent
11console.log(window.navigator.userAgent);
12
13// Display the width and height of the viewport
14console.log(`Width: ${window.innerWidth}, 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
객체를 사용하십시오.
1<!DOCTYPE html>
2<html>
3 <head>
4 <title>Example of DOM Manipulation</title>
5 </head>
6 <body>
7 <div id="content">Hello, World!</div>
8 <button id="changeText">Change Text</button>
9 </body>
10</html>
DOM 요소 가져오기
JavaScript는 DOM의 요소에 접근하기 위한 여러 가지 메서드를 제공합니다.
document.getElementById()
:id
속성으로 요소 가져오기document.getElementsByClassName()
: 클래스 이름으로 요소 가져오기 (HTMLCollection)document.getElementsByTagName()
: 태그 이름으로 요소 가져오기 (HTMLCollection)document.querySelector()
: CSS 선택자를 사용하여 가장 먼저 일치하는 요소 가져오기document.querySelectorAll()
: CSS 선택자를 사용하여 모든 일치하는 요소 가져오기 (NodeList)
예시: getElementById
및 querySelector
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"
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
: 모든 유형의 자식 노드에 접근하기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<ul id="list">
2 <li>Item 1</li>
3 <li>Item 2</li>
4</ul>
5<button id="addItem">Add Item</button>
6
7<script>
8 const list = document.getElementById('list');
9 const addItemButton = document.getElementById('addItem');
10
11 addItemButton.addEventListener('click', () => {
12 const newItem = document.createElement('li');
13 newItem.textContent = 'New Item';
14 list.appendChild(newItem);
15 });
16</script>
이 코드에서 "항목 추가" 버튼을 클릭하면 목록에 새 <li>
요소가 추가됩니다.
요약
- JavaScript DOM 조작을 사용하면 HTML 문서 내의 요소를 가져오고, 변경하고, 생성하고, 삭제할 수 있습니다.
getElementById()
및querySelector()
와 같은 메서드를 사용하여 요소를 가져올 수 있습니다.textContent
또는innerHTML
을 사용해 텍스트와 HTML을 변경하고,setAttribute()
를 사용해 속성을 조작합니다.createElement()
을 사용해 새 요소를 생성하고remove()
를 사용해 이를 삭제할 수 있습니다.- 이벤트 처리를 통해 사용자 조작에 반응하는 대화형 웹 페이지를 만들 수 있습니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.