Dseok의 실전 예제로 웹개발 한방에 끝내기

웹개발, 혼자 하려니 막막하고 힘드시죠? 저 또한 그렇습니다. 힘든 웹개발... 실전 예제를 통해 함께 공부해요!!!!😁📕

Javascript

[Dseok의 코딩스터디] html 부모 요소의 자식 요소 배열로 가져오기 & 동적 추가 기능 구현

Dseok 2025. 2. 21. 21:50
반응형
SMALL

📌 개요

HTML에서 특정 부모 요소 안의 자식 요소들을 배열로 가져와 속성을 컨트롤하거나, 사용자가 입력한 내용을 동적으로 추가하는 기능을 구현하는 방법을 설명합니다.

이를 위해 HTML, CSS, JavaScript를 활용하여 리스트 관리 시스템을 만들어 보겠습니다.

html 구현하기

📌 구현 목표

  1. 부모 요소 안의 자식 요소들을 배열로 가져와서 속성 변경
  2. 버튼 클릭 시 새로운 자식 요소를 추가하는 기능
  3. 입력한 텍스트 값을 리스트로 추가하는 기능
 

📌 HTML 구조

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>부모 요소 안의 자식 요소 컨트롤</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h2>자식 요소 컨트롤 & 추가</h2>
        <ul id="itemList">
            <li class="item">첫 번째 아이템</li>
            <li class="item">두 번째 아이템</li>
            <li class="item">세 번째 아이템</li>
        </ul>
        <button id="changeColor">배경색 변경</button>
        <input type="text" id="newItem" placeholder="추가할 아이템 입력">
        <button id="addItem">추가</button>
        <button id="removeLastItem">마지막 항목 삭제</button>
        <button id="sortItems">정렬</button>
    </div>
    <script src="script.js"></script>
</body>
</html>
 

📌 CSS 스타일 (styles.css)

body {
    font-family: Arial, sans-serif;
    text-align: center;
}
.container {
    width: 300px;
    margin: 20px auto;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 5px;
}
ul {
    list-style: none;
    padding: 0;
}
li {
    padding: 10px;
    border: 1px solid #ddd;
    margin: 5px 0;
    cursor: pointer;
}
.highlight {
    background-color: yellow;
}
 

📌 JavaScript (script.js)

document.addEventListener("DOMContentLoaded", function() {
    const itemList = document.getElementById("itemList");
    const items = itemList.children;
    const changeColorBtn = document.getElementById("changeColor");
    const addItemBtn = document.getElementById("addItem");
    const newItemInput = document.getElementById("newItem");
    const removeLastItemBtn = document.getElementById("removeLastItem");
    const sortItemsBtn = document.getElementById("sortItems");

    // 부모 요소 안의 모든 자식 요소를 배열로 가져와서 배경색 변경
    changeColorBtn.addEventListener("click", function() {
        Array.from(items).forEach(item => {
            item.classList.toggle("highlight");
        });
    });

    // 입력한 내용을 동적으로 추가하는 기능
    addItemBtn.addEventListener("click", function() {
        const newText = newItemInput.value.trim();
        if (newText !== "") {
            const newLi = document.createElement("li");
            newLi.textContent = newText;
            newLi.classList.add("item");
            itemList.appendChild(newLi);
            newItemInput.value = "";
        }
    });

    // 마지막 항목 삭제 기능
    removeLastItemBtn.addEventListener("click", function() {
        if (itemList.children.length > 0) {
            itemList.removeChild(itemList.lastElementChild);
        }
    });

    // 리스트 정렬 기능
    sortItemsBtn.addEventListener("click", function() {
        const sortedItems = Array.from(itemList.children)
            .map(item => item.textContent)
            .sort();
        itemList.innerHTML = "";
        sortedItems.forEach(text => {
            const li = document.createElement("li");
            li.textContent = text;
            li.classList.add("item");
            itemList.appendChild(li);
        });
    });
});
 

📌 마무리 🎯

  • children을 사용하면 부모 요소 안의 자식 요소를 배열처럼 가져와 컨트롤 가능.
  • createElement() appendChild()를 사용하면 사용자가 입력한 내용을 동적으로 추가 가능.
  • .classList.toggle()을 활용하면 스타일을 쉽게 변경할 수 있음.
  • removeChild()를 사용하면 마지막 자식 요소를 삭제 가능.
  • .sort()를 활용하면 리스트를 정렬 가능.
반응형
LIST