카테고리 없음
노드 추가, 삭제, 이동
yunajoe
2022. 11. 20. 08:08
노드추가하기
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JS with Codeit</title>
</head>
<body>
<div>
<h1>오늘 할 일</h1>
<ol id="today">
<li>자바스크립트 공부</li>
<li>고양이 화장실 청소</li>
<li>고양이 장난감 쇼핑</li>
</ol>
<h1>내일 할 일</h1>
<ol id="tomorrow">
<li>자바스크립트 공부</li>
<li>뮤지컬 공연 예매</li>
<li>유튜브 시청</li>
</ol>
</div>
<script src="index.js"></script>
</body>
</html>
const today = document.querySelector('#today');
today.innerHTML = '<li>처음</li>' + today.innerHTML;
today.innerHTML = today.innerHTML + '<li>마지막</li>';
today.outerHTML = '<p>이전</p>' + today.outerHTML;
const newToday = document.querySelector('#today');
newToday.outerHTML = newToday.outerHTML + '<p>다음</p>';
const tomorrow = document.querySelector('#tomorrow');
// 1. 요소 노드 만들기 ==> document.createElement('태그이름')
const first = document.createElement('li');
// 2. 요소 노드 꾸미기 ==> textContent, innerHTML...
first.textContent = '처음';
// 3. 요소 노드 추가하기 ==> prepend, append, after, before
tomorrow.prepend(first);
const last = document.createElement('li');
last.textContent = '마지막';
tomorrow.append(last);
const prev = document.createElement('p');
prev.textContent = '이전';
tomorrow.before("문자열", prev);
const next = document.createElement('p');
next.textContent = '다음';
tomorrow.after(next);

노드 삭제하기
const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');
// 노드 삭제하기
tomorrow.remove(); // 모든 노드 삭제
today.children[0].remove(); // 특정 노드 삭제

노드 이동하기
const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');
// 노드 이동하기 ==> append, prepend, before, after
today.append(tomorrow.children[0]); // today의 마지막 노드로 이동
today.prepend(tomorrow.children[0]); // today의 첫번째 노드로 이동

const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');
// today.children[0] 요소를 tomorrow.children[1](뮤지컬 공연 예매) 다음으로 이동
tomorrow.children[1].after(today.children[0]);
// today.children[1] 요소를 tomorrow.children[3](유튜브 시청) 이전으로 이동
tomorrow.children[3].before(today.children[1])
// today.children[0] 요소를 tomorrow.lastElementChild(유튜브 시청) 이전으로 이동
tomorrow.lastElementChild.before(today.children[0])

실습하기
- li 태그이름을 가진 요소 노드를 만든 다음
- 그 요소 노드에 파라미터로 전달받은 오늘 할 일(text)을 담고
- <ul id="to-do-list"></ul>태그의 마지막 자식 요소 노드로 추가
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>오늘 할 일</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<h2 class="title">오늘 할 일</h2>
<ul id="to-do-list"></ul>
</div>
<script src="index.js"></script>
</body>
</html>
const toDoList = document.querySelector('#to-do-list');
function addNewTodo(text) {
const lis = document.createElement('li');
lis.textContent = text;
toDoList.append(lis);
}
// 테스트 코드
addNewTodo('자바스크립트 공부하기');
addNewTodo('고양이 화장실 청소하기');
addNewTodo('고양이 장난감 쇼핑하기');