본문 바로가기

JavaScript/Interactive JavaScript

[JavaScript] 요소 노드 추가 / 이동 / 삭제

1.  요소 노드 추가

 

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. 요소 노드 추가하기: NODE.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 toDoList = document.querySelector('#to-do-list');

function addNewTodo(text) {
	// 여기에 코드를 작성하세요
	const today = document.createElement('li'); // 요소 노드 만들기
	today.textContent = text; // 요소 노드 꾸미기
	toDoList.append(today); // 요소 노드 추가하기 (자식 요소)
	
}

// 테스트 코드
addNewTodo('자바스크립트 공부하기');
addNewTodo('고양이 화장실 청소하기');
addNewTodo('고양이 장난감 쇼핑하기');

2. 요소 노드 삭제 (remove)

 

const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');

// 노드 삭제하기: Node.remove()
tomorrow.remove();
today.children[2].remove(); // today 노드의 자식요소 중에서 2번 인덱스 삭제

3. 요소 노드 이동 (prepend, append, before, after)

 

const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');

// 노드 이동하기: prepend, append, before, after
today.append(tomorrow.children[1]); // tomorrow 노드의 자식요소 중 1번 인덱스를 today노드로 이동
tomorrow.children[1].after(today.children[1]); // today 노드의 1번 인덱스를 tomorrow 노드의 자식요소 2번인덱스 다음으로 이동
tomorrow.children[2].before(today.children[1]); // today 노드의 1번 인덱스를 tomorrow 노드의 자식요소 2번인덱스 전으로 이동
tomorrow.lastElementChild.before(today.children[1]); // today 노드의 1번 인덱스를 tomorrow 노드의 마지막 자식요소 전으로 이동