반응형
SMALL
📌 개요
HTML에서 특정 부모 요소 안의 자식 요소들을 배열로 가져와 속성을 컨트롤하거나, 사용자가 입력한 내용을 동적으로 추가하는 기능을 구현하는 방법을 설명합니다.
이를 위해 HTML, CSS, JavaScript를 활용하여 리스트 관리 시스템을 만들어 보겠습니다.

📌 구현 목표
- 부모 요소 안의 자식 요소들을 배열로 가져와서 속성 변경
- 버튼 클릭 시 새로운 자식 요소를 추가하는 기능
- 입력한 텍스트 값을 리스트로 추가하는 기능
📌 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
'Javascript' 카테고리의 다른 글
[Dseok의 코딩스터디] JavaScript & jQuery를 사용하여 인라인 CSS 속성 제거하는 5가지 방법 (0) | 2025.02.27 |
---|---|
[Dseok의 코딩스터디] javascript로 html dom 컨트롤 및 조작 한방에 끝내기 | li 요소에 on 클래스 추가 및 동적 요소 생성 (0) | 2025.02.23 |
[Dseok의 코딩스터디] 자바스크립트 switch문 (0) | 2025.02.19 |
[Dseok의 코딩스터디] 비밀번호 보이게하기, 숨기기 기능 구현 (0) | 2024.11.04 |
[Dseok의 코딩스터디] includes()메서드로 검색어 필터링 기능 만들어보기 (0) | 2024.10.04 |