동적으로 HTML 문서에서 노드를 삭제하려면 먼저 부모 노드를 알아야한다. 먼저 부모 노드를 선정하고 그 자식 노드 중에서 제거하고자 하는 노드를 선정하고, removeChild() 메서드를 이용한다.
메서드 | 설명 |
document.removeChild(요소) | 자식노드 중 해당하는 요소 제거 (요소노드, 텍스트 노드 가능) |
element.textContent = " " | 해당 요소의 텍스트 노드 삭제 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div1">
<p id="p1">this is a paragraph.</p>
<p id="p2">this is another paragraph</p>
</div>
<script>
let para = document.querySelector("#div1");
let node = document.querySelector("#p1");
para.removeChild(node);
// p태그로 인식
// para.innerHTML = `<p id="p2"> this is another paragraph</p>`;
// 텍스트로 인식
// para.textContent = `<p id="p2"> this is another paragraph</p>`;
// para.innerHTML = para.nodeValue;
// console.log(para.nodeValue);
// console.log(para.children);
// console.log(para.children[0].childNodes[0].nodeValue);
</script>
</body>
</html>
'웹 프로그래밍 기초 > DOM 문서객체' 카테고리의 다른 글
HTML 요소 (Noes) 변경 (0) | 2025.04.13 |
---|---|
HTML DOM 요소 (0) | 2025.04.12 |
addEventListener 실습예제 (2) | 2025.04.11 |
addEventListener (0) | 2025.04.11 |
이벤트 (1) | 2025.04.11 |