>  기사  >  웹 프론트엔드  >  DOM 조작: DOM 요소 선택 및 조작

DOM 조작: DOM 요소 선택 및 조작

PHPz
PHPz원래의
2024-08-09 12:34:32932검색

DOM Manipulation: Selecting and Manipulating DOM Elements

DOM 소개

DOM(문서 개체 모델)은 웹 개발에 중요한 개념입니다. 이는 개발자가 웹 페이지의 구조, 스타일 및 콘텐츠와 상호 작용하고 수정할 수 있도록 하는 프로그래밍 인터페이스 역할을 합니다. 웹페이지가 브라우저에 로드되면 HTML 문서는 각 노드가 요소, 속성 또는 텍스트를 나타내는 트리형 구조인 DOM으로 변환됩니다. 이 구조를 통해 개발자는 페이지의 일부에 동적으로 액세스하고 조작할 수 있으므로 웹 환경이 더욱 상호 작용적이고 매력적으로 만들어집니다.

DOM이 처음이시거나 익숙하지 않은 분들은 DOM을 집의 청사진이라고 생각하시면 됩니다. 집에서 가구를 재배치하거나 벽을 칠할 수 있는 것처럼 DOM을 사용하면 웹페이지가 로드된 후 웹페이지의 콘텐츠와 스타일을 변경할 수 있습니다.

요소 선택

DOM을 조작하기 전에 작업하려는 요소를 선택해야 합니다. JavaScript는 요소를 선택하는 여러 가지 방법을 제공하므로 웹 페이지의 다양한 부분과 상호 작용할 수 있습니다. 다음은 몇 가지 일반적인 방법을 살펴보겠습니다.

1. ID로 요소 선택

getElementById 메소드는 단일 요소를 선택하는 가장 간단한 방법 중 하나입니다. 지정된 ID와 일치하는 요소를 반환합니다.

// Selecting an element by ID
const heading = document.getElementById('heading');

이 예에서 제목은 이제 제목 ID가 있는 요소를 참조합니다. 이 참조를 사용하여 요소를 추가로 조작할 수 있습니다.

2. 클래스 이름으로 요소 선택

동일한 클래스를 가진 여러 요소를 선택하려면 getElementsByClassName 메소드를 사용할 수 있습니다. 이 메소드는 요소의 라이브 HTMLCollection을 반환합니다.

// Selecting elements by class name
const items = document.getElementsByClassName('item');

이제 items 변수는 클래스 이름이 item인 모든 요소의 컬렉션을 보유합니다. 이 방법은 여러 요소에 동일한 작업을 적용해야 할 때 특히 유용합니다.

3. CSS 선택기를 사용하여 요소 선택

querySelector 및 querySelectorAll 메소드를 사용하면 CSS 선택기를 사용하여 요소를 선택할 수 있습니다. 이러한 방법은 다목적이며 태그 이름, 클래스, ID 또는 기타 유효한 CSS 선택기로 요소를 타겟팅하는 데 사용할 수 있습니다.

// Selecting a single element using a CSS selector
const button = document.querySelector('button');

// Selecting multiple elements using a CSS selector
const listItems = document.querySelectorAll('li');

querySelector는 선택기와 일치하는 첫 번째 요소를 선택하고, querySelectorAll은 일치하는 모든 요소를 ​​선택하고 배열과 유사한 NodeList를 반환합니다.

요소 조작

요소를 선택한 후에는 해당 요소를 조작하여 콘텐츠, 속성, 스타일을 변경할 수 있습니다. 이를 통해 사용자 상호 작용이나 기타 이벤트에 반응하는 동적 웹 페이지를 만들 수 있습니다.

1. 텍스트 내용 변경

textContent 속성을 사용하면 요소 내의 텍스트를 변경할 수 있습니다. 이는 사용자 입력이나 기타 조건에 따라 콘텐츠를 동적으로 업데이트하는 데 유용합니다.

// Changing text content
heading.textContent = 'Hello, World!';

이 예에서는 제목이 참조하는 요소 내부의 텍스트가 "Hello, World!"로 업데이트됩니다.

2. 속성 변경

setAttribute 메소드를 사용하면 src, href, alt 또는 비활성화와 같은 요소의 속성을 수정할 수 있습니다.

// Changing an attribute
button.setAttribute('disabled', true);

여기서 비활성화 속성을 true로 설정하면 버튼이 비활성화됩니다. 특정 조건이 충족될 때까지 사용자 상호작용을 방지하는 데 사용할 수 있습니다.

3. 스타일 바꾸기

스타일 속성을 사용하면 요소의 인라인 CSS 스타일을 수정할 수 있습니다. 색상, 배경색상, 글꼴 크기 등과 같은 속성을 변경할 수 있습니다.

// Changing styles
heading.style.color = 'blue';

이 예에서는 제목 요소 내의 텍스트 색상이 파란색으로 변경되었습니다.

요소 생성 및 제거

기존 요소를 수정하는 것 외에도 새 요소를 만들어 DOM에 추가하거나 더 이상 필요하지 않은 요소를 제거할 수 있습니다.

1. 새로운 요소 생성

createElement 메소드를 사용하여 새 요소를 생성할 수 있습니다. 일단 생성되면 해당 속성을 설정하고 DOM의 기존 요소에 추가할 수 있습니다.

// Creating a new element
const newElement = document.createElement('p');
newElement.textContent = 'This is a new paragraph.';
document.body.appendChild(newElement);

이 예에서는 새로운

요소가 생성되고 텍스트 내용이 설정되며 요소.

2. 요소 제거

DOM에서 요소를 제거하려면 제거 메소드를 사용할 수 있습니다. 이는 페이지의 콘텐츠를 동적으로 관리하는 데 특히 유용합니다.

// Removing an element
const oldElement = document.getElementById('old-element');
oldElement.remove();

여기서 ID가 old-element인 요소가 DOM에서 제거되어 웹페이지에서도 효과적으로 삭제됩니다.

실제 사례: 할 일 목록

이러한 개념이 실제로 어떻게 작동하는지 확인하기 위해 간단한 To-Do List 애플리케이션을 구축해 보겠습니다. 이 예는 실제 시나리오에서 DOM 요소를 선택하고 조작하는 방법을 보여줍니다.

HTML Structure

First, let's create the HTML structure for our To-Do List.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>To-Do List</title>
</head>
<body>
  <h1 id="heading">To-Do List</h1>
  <ul id="todo-list"></ul>
  <input type="text" id="new-todo" placeholder="New to-do">
  <button id="add-todo">Add To-Do</button>
</body>
</html>

In this structure:

  • We have a heading (

    ) with an ID of heading.

  • An unordered list (
      ) with an ID of todo-list, where our to-do items will be displayed.
    • An input field for adding new to-do items, with an ID of new-todo.
    • A button with an ID of add-todo to add new items to the list.

    JavaScript for Interactivity

    Next, we'll add some JavaScript to make the To-Do List interactive.

    <script>
      // Selecting elements
      const todoList = document.getElementById('todo-list');
      const newTodoInput = document.getElementById('new-todo');
      const addTodoButton = document.getElementById('add-todo');
    
      // Adding a new to-do item
      addTodoButton.addEventListener('click', () => {
        const newTodoText = newTodoInput.value;
        if (newTodoText === '') return; // Prevent adding empty to-do items
    
        // Create a new list item
        const newTodoItem = document.createElement('li');
        newTodoItem.textContent = newTodoText;
    
        // Append the new item to the list
        todoList.appendChild(newTodoItem);
    
        // Clear the input field
        newTodoInput.value = '';
      });
    </script>
    

    Explanation:

    1. Selecting Elements: We begin by selecting the necessary elements using their IDs.
    2. Event Listener: We add a click event listener to the "Add To-Do" button. When clicked, the event listener function is triggered.
    3. Input Validation: Inside the function, we first check if the input field is empty to prevent adding empty to-do items.
    4. Creating a New Element: If the input is not empty, we create a new
    5. element and set its text content to the value entered in the input field.
    6. Appending the New Item: The new
    7. is then appended to the existing
        element.
      • Clearing the Input Field: Finally, the input field is cleared, ready for the next to-do item.

    This simple application demonstrates the power of DOM manipulation in creating interactive and dynamic web pages.

    Conclusion

    DOM manipulation is a fundamental skill for any web developer. By understanding how to select and manipulate DOM elements, you can create web pages that are not only static but also responsive to user interactions. The examples provided in this article serve as a foundation for more advanced topics, such as event handling, animations, and dynamic content loading.

    By practicing these techniques and applying them to real-world scenarios, you'll gain a deeper understanding of how the web works and be well on your way to mastering front-end development.

    위 내용은 DOM 조작: DOM 요소 선택 및 조작의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.