JavaScript 로 DOM 속성 탐색

CSSBeginner
지금 연습하기

소개

이 랩에서는 참가자들이 대화형 HTML 문서를 생성하고 JavaScript 를 사용하여 다양한 문서 속성에 접근하고 조작함으로써 JavaScript 의 Document Object Model (DOM) 속성을 탐구합니다. 이 랩은 문서 제목, URL, 링크, 이미지, 본문 내용과 같은 주요 DOM 속성을 이해하기 위한 실습 중심의 접근 방식을 제공합니다.

단계별 과정을 통해 학습자는 먼저 기본적인 HTML 구조를 생성한 다음, JavaScript 를 사용하여 점진적으로 다양한 문서 속성과 상호 작용합니다. 문서 제목에 접근하고, URL 과 링크를 검색하고, 이미지 수를 세고, 문서 본문 및 쿠키 속성을 탐구하는 등의 방법을 통해 참가자들은 JavaScript 가 웹 페이지 요소 및 메타데이터와 동적으로 상호 작용하는 방식을 실질적으로 이해하게 됩니다.

기본 구조를 갖춘 HTML 문서 생성

이 단계에서는 JavaScript 에서 DOM 속성을 탐구하기 위한 기반이 될 기본적인 HTML 문서를 생성하는 방법을 배웁니다. WebIDE 를 사용하여 필수 요소를 포함하는 간단한 구조의 HTML 파일을 생성합니다.

먼저 WebIDE 에서 ~/project 디렉토리로 이동합니다. 파일 탐색기에서 마우스 오른쪽 버튼을 클릭하고 "New File"을 선택하여 index.html이라는 새 파일을 생성합니다.

다음 HTML 코드를 복사하여 index.html 파일에 붙여넣습니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>DOM Properties Exploration</title>
  </head>
  <body>
    <h1>Welcome to DOM Properties Lab</h1>
    <p>This page will help us explore JavaScript DOM properties.</p>
    <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
    <img src="https://example.com/another-image.jpg" alt="Another Image" />
  </body>
</html>

이 HTML 문서의 주요 구성 요소를 살펴보겠습니다.

  • <!DOCTYPE html>은 이것을 HTML5 문서로 선언합니다.
  • <html lang="en">은 문서의 언어를 설정합니다.
  • <head>는 문서에 대한 메타데이터를 포함합니다.
  • <title>은 페이지 제목을 설정하며, 이는 이후 단계에서 사용됩니다.
  • <body>는 페이지의 보이는 내용을 포함합니다.
  • 이후 단계에서 이미지 관련 DOM 속성을 시연하기 위해 두 개의 <img> 태그를 포함했습니다.

이 파일을 브라우저에서 열 때의 예시 출력:

[제목이 "DOM Properties Exploration"인 웹 페이지가
 "Welcome to DOM Properties Lab"을 표시하고
 "This page will help us explore JavaScript DOM properties."를 표시합니다.]

이 간단한 HTML 구조는 DOM 속성 탐구 랩을 위한 완벽한 시작점을 제공합니다.

document.title 속성 접근

이 단계에서는 JavaScript 를 사용하여 문서 제목 속성에 접근하는 방법을 배웁니다. 이전 단계에서 생성한 HTML 파일을 기반으로 문서의 제목을 검색하고 조작하는 방법을 시연합니다.

WebIDE 를 사용하여 ~/project 디렉토리에 script.js라는 새 파일을 생성합니다. 다음 JavaScript 코드를 추가합니다.

// Access the document title
console.log("Document Title:", document.title);

// Modify the document title
function changeTitle() {
  document.title = "Updated DOM Properties Lab";
  console.log("New Document Title:", document.title);
}

// Add a button to demonstrate title change
const button = document.createElement("button");
button.textContent = "Change Title";
button.onclick = changeTitle;
document.body.appendChild(button);

이제 index.html 파일을 업데이트하여 JavaScript 파일을 포함합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>DOM Properties Exploration</title>
  </head>
  <body>
    <h1>Welcome to DOM Properties Lab</h1>
    <p>This page will help us explore JavaScript DOM properties.</p>
    <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
    <img src="https://example.com/another-image.jpg" alt="Another Image" />

    <script src="script.js"></script>
  </body>
</html>

이 HTML 파일을 브라우저에서 열면 다음과 같은 동작을 볼 수 있습니다.

브라우저 콘솔의 예시 출력:

Document Title: DOM Properties Exploration

"Change Title" 버튼을 클릭하면:

New Document Title: Updated DOM Properties Lab

시연된 주요 개념:

  • document.title 속성은 현재 페이지 제목을 검색합니다.
  • JavaScript 를 사용하여 문서 제목을 동적으로 변경할 수 있습니다.
  • 제목은 브라우저 탭에 나타나며 런타임에 수정할 수 있습니다.

문서 URL 및 링크 가져오기

이 단계에서는 JavaScript DOM 속성을 사용하여 문서의 URL 에 접근하고 링크에 대한 정보를 검색하는 방법을 배웁니다. 이러한 기능을 시연하기 위해 script.js 파일을 업데이트합니다.

WebIDE 에서 script.js 파일을 열고 다음 코드를 추가합니다.

// Retrieve and display the current document URL
console.log("Current Document URL:", document.URL);

// Get the number of links on the page
const linkCount = document.links.length;
console.log("Total Number of Links:", linkCount);

// Display information about all links
function displayLinkInfo() {
  const links = document.links;
  console.log("Link Information:");
  for (let i = 0; i < links.length; i++) {
    console.log(`Link ${i + 1}:`);
    console.log(`  Href: ${links[i].href}`);
    console.log(`  Text: ${links[i].text}`);
  }
}

// Add a button to show link information
const linkButton = document.createElement("button");
linkButton.textContent = "Show Link Details";
linkButton.onclick = displayLinkInfo;
document.body.appendChild(linkButton);

index.html 파일을 업데이트하여 몇 개의 추가 링크를 포함합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>DOM Properties Exploration</title>
  </head>
  <body>
    <h1>Welcome to DOM Properties Lab</h1>
    <p>This page will help us explore JavaScript DOM properties.</p>

    <div>
      <a href="https://example.com">Example Website</a>
      <a href="https://labex.io">LabEx Learning Platform</a>
    </div>

    <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
    <img src="https://example.com/another-image.jpg" alt="Another Image" />

    <script src="script.js"></script>
  </body>
</html>

브라우저 콘솔의 예시 출력:

Current Document URL: file:///home/labex/project/index.html
Total Number of Links: 2

Link Information:
Link 1:
  Href: https://example.com
  Text: Example Website
Link 2:
  Href: https://labex.io
  Text: LabEx Learning Platform

시연된 주요 개념:

  • document.URL은 현재 문서의 전체 URL 을 검색합니다.
  • document.links는 페이지의 모든 링크 컬렉션을 제공합니다.
  • 링크를 반복하여 hreftext와 같은 속성에 접근할 수 있습니다.

페이지 내 이미지 개수 세기 및 표시

이 단계에서는 JavaScript DOM 속성을 사용하여 웹 페이지의 이미지에 대한 정보를 세고 표시하는 방법을 배웁니다. 이미지 관련 기능을 탐색하기 위해 script.js 파일을 업데이트합니다.

WebIDE 에서 script.js 파일을 열고 다음 코드를 추가합니다.

// Count the number of images on the page
const imageCount = document.images.length;
console.log("Total Number of Images:", imageCount);

// Function to display image details
function displayImageInfo() {
  const images = document.images;
  console.log("Image Information:");
  for (let i = 0; i < images.length; i++) {
    console.log(`Image ${i + 1}:`);
    console.log(`  Source: ${images[i].src}`);
    console.log(`  Alt Text: ${images[i].alt}`);
  }
}

// Create a button to show image details
const imageButton = document.createElement("button");
imageButton.textContent = "Show Image Details";
imageButton.onclick = displayImageInfo;
document.body.appendChild(imageButton);

// Add a simple image information display area
const infoDiv = document.createElement("div");
infoDiv.id = "image-info";
document.body.appendChild(infoDiv);

// Update the div with image count
infoDiv.textContent = `Number of Images: ${imageCount}`;

index.html 파일을 업데이트하여 다양한 속성을 가진 더 많은 이미지를 포함합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>DOM Properties Exploration</title>
  </head>
  <body>
    <h1>Welcome to DOM Properties Lab</h1>
    <p>This page will help us explore JavaScript DOM properties.</p>

    <div>
      <a href="https://example.com">Example Website</a>
      <a href="https://labex.io">LabEx Learning Platform</a>
    </div>

    <div id="image-container">
      <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
      <img src="https://example.com/another-image.jpg" alt="Another Image" />
      <img src="https://example.com/third-image.png" alt="Third Image" />
    </div>

    <script src="script.js"></script>
  </body>
</html>

브라우저 콘솔의 예시 출력:

Total Number of Images: 3
Image Information:
Image 1:
  Source: https://example.com/sample-image.jpg
  Alt Text: Sample Image
Image 2:
  Source: https://example.com/another-image.jpg
  Alt Text: Another Image
Image 3:
  Source: https://example.com/third-image.png
  Alt Text: Third Image

시연된 주요 개념:

  • document.images는 페이지의 모든 이미지 컬렉션을 제공합니다.
  • srcalt와 같은 이미지 속성에 접근할 수 있습니다.
  • JavaScript 를 사용하여 페이지 요소를 동적으로 생성하고 조작합니다.

이 단계에서는 JavaScript 에서 문서 본문 및 쿠키 속성을 탐색하여 페이지 콘텐츠를 조작하고 브라우저 쿠키를 사용하는 방법을 배웁니다.

WebIDE 에서 script.js 파일을 열고 다음 코드를 추가합니다.

// Demonstrate document body manipulation
function modifyBodyContent() {
  // Access and modify document body
  const body = document.body;
  console.log("Original Body Inner HTML:", body.innerHTML);

  // Create a new paragraph element
  const newParagraph = document.createElement("p");
  newParagraph.textContent =
    "This paragraph was dynamically added to the body!";
  body.appendChild(newParagraph);

  console.log("Updated Body Inner HTML:", body.innerHTML);
}

// Demonstrate cookie properties
function manageCookies() {
  // Set a new cookie
  document.cookie =
    "labExperience=JavaScript DOM; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

  // Display all cookies
  console.log("Current Cookies:", document.cookie);

  // Create a button to show cookies
  const cookieButton = document.createElement("button");
  cookieButton.textContent = "Show Cookies";
  cookieButton.onclick = () => {
    alert(`Cookies: ${document.cookie}`);
  };
  document.body.appendChild(cookieButton);
}

// Create buttons to trigger demonstrations
const bodyButton = document.createElement("button");
bodyButton.textContent = "Modify Body Content";
bodyButton.onclick = modifyBodyContent;
document.body.appendChild(bodyButton);

const cookieButton = document.createElement("button");
cookieButton.textContent = "Manage Cookies";
cookieButton.onclick = manageCookies;
document.body.appendChild(cookieButton);

호환성을 위해 index.html 파일을 업데이트합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>DOM Properties Exploration</title>
  </head>
  <body>
    <h1>Welcome to DOM Properties Lab</h1>
    <p>This page will help us explore JavaScript DOM properties.</p>

    <div>
      <a href="https://example.com">Example Website</a>
      <a href="https://labex.io">LabEx Learning Platform</a>
    </div>

    <div id="image-container">
      <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
      <img src="https://example.com/another-image.jpg" alt="Another Image" />
      <img src="https://example.com/third-image.png" alt="Third Image" />
    </div>

    <script src="script.js"></script>
  </body>
</html>

브라우저 콘솔의 예시 출력:

// After clicking "Modify Body Content"
Original Body Inner HTML: [initial HTML content]
Updated Body Inner HTML: [HTML content with new paragraph added]

// After clicking "Manage Cookies"
Current Cookies: labExperience=JavaScript DOM

시연된 주요 개념:

  • document.body에 접근하고 수정하기
  • 새로운 요소를 동적으로 생성하고 추가하기
  • 브라우저 쿠키 설정 및 읽기
  • JavaScript 를 사용하여 문서 속성과 상호 작용하기

요약

이 Lab 에서 참가자들은 구조화된 HTML 문서를 생성하고 다양한 속성 접근 기술을 구현하여 JavaScript 를 사용하여 DOM (Document Object Model, 문서 객체 모델) 속성을 탐색하는 방법을 배웁니다. Lab 은 제목, 본문, 이미지와 같은 필수 요소를 포함하는 기본 HTML 파일을 구성하는 것으로 시작하여 DOM 상호 작용을 이해하기 위한 기반을 제공합니다.

실습은 학습자가 제목, URL, 링크 및 이미지 개수와 같은 다양한 문서 속성에 접근하도록 안내하며, JavaScript 가 웹 페이지 메타데이터를 동적으로 검색하고 조작할 수 있는 방법을 보여줍니다. 이러한 단계를 통해 참가자들은 기본적인 DOM 속성을 검사하고 상호 작용하는 실질적인 경험을 얻어 클라이언트 측 웹 개발 기술에 대한 이해를 높입니다.